ruby:如何在本地上下文中加载.rb文件 [英] ruby: how to load .rb file in the local context

查看:212
本文介绍了ruby:如何在本地上下文中加载.rb文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Ruby中完成此简单任务?
我有一些简单的配置文件

How this simple task can be done in Ruby?
I have some simple config file

=== config.rb
config = { 'var' => 'val' }

我想从main.rb文件中定义的某种方法中加载配置文件,以使config.rb中的局部变量成为该方法的局部变量.
像这样:

I want to load config file from some method, defined in main.rb file so that the local variables from config.rb became local vars of that method.
Something like this:

=== main.rb
Class App
    def loader
        load('config.rb') # or smth like that
        p config['var']   # => "val"
    end
end

我知道我可以在config.rb中使用全局变量,然后在完成后取消定义它们,但我希望有一个红宝石方法)

I know that i can use global vars in config.rb and then undefine them when done, but i hope there's a ruby way )

推荐答案

您当然可以使用eval和File.read破解一个解决方案,但是事实很难,这会向您发出一个信号,表明它不像红宝石一样解决您遇到的问题的方法.两种替代设计是将yaml用于您的配置api,或定义一个简单的dsl.

You certainly could hack out a solution using eval and File.read, but the fact this is hard should give you a signal that this is not a ruby-like way to solve the problem you have. Two alternative designs would be using yaml for your config api, or defining a simple dsl.

YAML情况最简单,您只需在main.rb中输入以下内容:

The YAML case is the easiest, you'd simply have something like this in main.rb:

Class App
  def loader
      config = YAML.load('config.yml')
      p config['var']   # => "val"
  end
end

,您的配置文件如下所示:

and your config file would look like:

--- 
var: val

这篇关于ruby:如何在本地上下文中加载.rb文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆