Created
July 23, 2013 22:30
-
-
Save msheakoski/6066746 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Is there a better way to simplify this such as instance_eval or another way to | |
# dynamically evaluate code in a limited context? | |
# | |
# What I'm trying to accomplish: | |
# | |
# - I have HTML widgets that accept form posts so they each have a basic input | |
# handler written in Ruby that for managability reasons is stored in the | |
# database. I'm aware of the dangers of eval. The code is from a trusted | |
# source only. | |
# | |
# - To reduce errors and potential problems, the eval'd code should not be able | |
# to access or modify variables or methods in the context of MyController. | |
# Anything I want to share will be explicitly passed to the handler. | |
# | |
# Questions: | |
# | |
# - I'm guessing that nothing can be done to limit access to constants and | |
# global variables? | |
# | |
# - Since klass is not a constant, will it be garbage collected and safe from | |
# memory leaks? | |
# Just something to mimic a basic Rails controller | |
class MyController | |
attr_accessor :params | |
def initialize | |
self.params = {controller: 'my_controller', action: 'some_action'} | |
end | |
def some_action | |
secret_var = 'shhhh!' | |
widget_handler = Class.new do | |
def run(params) | |
ruby_code_loaded_from_database = <<-RUBY | |
params[:foo] = 'bar' | |
puts "params_in_handler: \#{params}, secret_var_defined_in_handler?: \#{!! defined?(secret_var)}" | |
RUBY | |
eval ruby_code_loaded_from_database | |
end | |
end | |
handler = widget_handler.new | |
handler.run params.dup | |
puts "params_in_action: #{params}" | |
end | |
end | |
controller = MyController.new | |
controller.some_action |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment