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
?
Other alternatives:
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
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
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With