Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: How to import a variable from another file?

Tags:

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

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.

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

like image 623
ghickman Avatar asked Dec 20 '11 10:12

ghickman


2 Answers

Other alternatives:

YAML (or JSON)

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

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

like image 116
Carl Suster Avatar answered Sep 26 '22 22:09

Carl Suster


The path to the file is wrong. It needs to include a slash if it isn't loaded from $LOAD_PATH.

Your LoadError is being caught silently.

If you do this:

VENV_FOLDER = '.'

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

puts VENV_FOLDER

Then you'll see it works.

Better still:

VENV_FOLDER = '.'

require File.expand_path('../local_config.rb', __FILE__) rescue LoadError

puts VENV_FOLDER

Since the second version doesn't depend on the PWD of the user who invokes the script.

Constant re-assignment is a bad idea however. Ruby will let you do it, but you'll get a warning. I believe your confusion was just with the LoadError though.

like image 35
d11wtq Avatar answered Sep 25 '22 22:09

d11wtq