Ruby:如何从另一个文件导入变量? [英] Ruby: How to import a variable from another file?

查看:51
本文介绍了Ruby:如何从另一个文件导入变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个本地配置文件以与指南针一起使用,以便我们可以处理开发人员机器上的不同导入路径.到目前为止,我已经尝试在异常块中导入文件,以防它不存在,然后进一步使用该变量:

I'm trying to create a local config file to use with compass so we can cope with differing import paths on developers' machines. So far I've tried to import the file inside an exception block, incase it doesn't exist, then use the variable further down:

local_config.rb

VENV_FOLDER = 'venv'

config.rb

VENV_FOLDER = '.'
begin
  require 'local_config.rb'
rescue LoadError
end
puts VENV_FOLDER

通常我是一名 Python 开发人员,所以我希望导入将 VENV_FOLDER 的值更改为 venv,但它仍然是 . 之后.

Normally I'm a Python developer so I'd expect the import to change the value of VENV_FOLDER to venv, however it's still . afterwards.

有没有办法以覆盖VENV_FOLDER的值的方式导入local_config.rb?

Is there a way to import local_config.rb in such a way that it overrides the value of VENV_FOLDER?

推荐答案

其他选择:

local_config.yml

venv_folder: 'venv'

config.rb

require 'yaml'

VENV_FOLDER = begin
  YAML.load_file('local_config.yml').fetch('venv_folder')
rescue Errno::ENOENT, KeyError
  '.'
end

puts VENV_FOLDER

类实例变量

您可以将值放在类实例变量中:

Class instance variable

You could put the value in a class instance variable:

local_config.rb

Config.venv = 'venv'

config.rb

class Config
  class << self ; attr_accessor :venv ; end
  self.venv = '.'
end

begin
  require './local_config.rb'
rescue LoadError
end

puts Config.venv

常数

此外,坚持使用常量的 ruby​​ 文件,以下内容的意图可能稍微清晰一些,并且避免了必须捕获异常.

Constants

Also, sticking to ruby files with constants, the following is perhaps marginally clearer in its intentions and avoids having to catch exceptions.

local_config.rb

VENV_FOLDER = 'venv'

config.rb

config_file = './local_config.rb'
require config_file if File.file? config_file
VENV_FOLDER ||= '.'

puts VENV_FOLDER

所有三种解决方案都有不同的机制来确保即使文件丢失或未按预期设置值也会设置该值.希望对你有帮助

All three solutions have different mechanisms for ensuring that the value will be set even if the file is missing or doesn't set the value as expected. Hope it's helpful

这篇关于Ruby:如何从另一个文件导入变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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