Skip to content

Instantly share code, notes, and snippets.

@msheakoski
Created July 23, 2013 22:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save msheakoski/6066746 to your computer and use it in GitHub Desktop.
Save msheakoski/6066746 to your computer and use it in GitHub Desktop.
# 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