Reputation: 8588
I have the following setup in my RailsApplication:
class MyClass
def self.perform_action! specific_name
init = YAML.load_file('path/to/file.yml')[specific_name]
input = init[:option1]
Here is the YAML file that gets loaded:
:MyName:
:option1: 'Data::Executables::SpecificFunction.new.run!'
:option2: 'Data::Executables::SpecificFunction.new.new_method'
Now, when I call MyClass.perform_action!(:MyName) it sure enough gets the value of :option1
and sets it equal to input
. What I need though is for that line to be executed; having it as a string is of no use.
How can that be done?
Upvotes: 1
Views: 1632
Reputation: 81
for more security, you can store in yaml file method's names only
:MyName:
:option1: 'new.run!'
:option2: 'new.new_method'
and use method send
class MyClass
def self.perform_action! specific_name
init = YAML.load_file('path/to/file.yml')[specific_name]
chain = init[:option1].split('.')
allowable_methods = Data::Executables::SpecificFunction
result = chain.reduce(allowable_methods){|target, method| target.send method}
Upvotes: 1
Reputation: 3368
To execute code in a string, you can use eval
:
class MyClass
def self.perform_action! specific_name
init = YAML.load_file('path/to/file.yml')[specific_name]
input = init[:option1]
result = eval(input)
I would only recommend this if you totally trust the YAML file, otherwise outsiders could have full access to your system, as eval
runs any code passed to it, malicious or not.
Upvotes: 0