Ruby 1.9.2 class_eval variables
-
25-02-2021 - |
Question
In Settingslogic fork allowing array as source, in ruby 1.8.7 everything is working, but in ruby 1.9.2 there is an error. The problem is within this part of the code:
self.class.class_eval <<-EndEval
def #{key}
return @#{key} if @#{key}
raise MissingSetting, "Missing setting '#{key}' in #{@section}" unless has_key? '#{key}'
value = fetch('#{key}')
@#{key} = value.is_a?(Hash) ? self.class.new(value, "'#{key}' section in #{@section}") : value
end
EndEval
@section == ["path_to_yml_file1", "path_to_yml_file2",...]
Looks like #{} is evaluated in some strange way, "#{@section}" seems to be an array, not a string. Can anybody explain this?
Error trace:
@section == ["User/project/config/defaults.yml", "/Users/project/config/development.yml"]
ruby-1.9.2-p290 :001 > Settings.keys
SyntaxError: (eval):3: syntax error, unexpected tSTRING_BEG, expecting keyword_end
...project/config/defaults.yml", "/Users/project...
... ^
(eval):3: syntax error, unexpected tSTRING_BEG, expecting keyword_end
...project/config/development.yml"]" unless has_key? 'front'
... ^
(eval):5: syntax error, unexpected tSTRING_BEG, expecting ')'
...project/config/defaults.yml", "/Users/project...
... ^
(eval):5: syntax error, unexpected tSTRING_BEG, expecting keyword_end
...project/config/development.yml"]") : value
... ^
(eval):5: syntax error, unexpected ')', expecting keyword_end
...project/config/development.yml"]") : value
... ^
from .../settingslogic-3b5d7d9cc319/lib/settingslogic.rb:198:in `class_eval'
Thanks for any help
Solution
You've made a fork from main settingslogic
. At that time it didn't support array as source, but now it does. Try to use main settingslogic
repository.
Your error now related to this string:
raise MissingSetting,
"Missing setting '#{key}' in #{@section}" unless has_key? '#{key}'
because in case of using array instead of string
./settings.yml
you get something like this:
[\"./settings.yml\"]
The same happens with @#{key}
assignment below. In main repository this code replaced to string concatenation.
OTHER TIPS
Try self.class_eval
or even without self, no need to get the name of class and self automatically assign to current object i.e. your class.