Skip to content

Instantly share code, notes, and snippets.

@remigijusj
Created March 8, 2011 18:19
Show Gist options
  • Save remigijusj/860695 to your computer and use it in GitHub Desktop.
Save remigijusj/860695 to your computer and use it in GitHub Desktop.
transfer local variables
class Binding
def publish(vars)
defs = vars.each_with_object("") do |var,str|
str << "define_method(:#{var}) { #{var} }\n"
str << "private :#{var}\n"
end
self.eval "self.class.module_eval { #{defs} }"
end
end
module Widget
class << self
def main(a, b)
# or just define a, b here..
binding.publish(local_variables)
other
b += 100
other
end
private
def other
puts a + b # <<< local variables, really??
end
end
end
Widget.main(17, 25) # => 42, 142
Widget.main(1, 2) # => 3, 103
p Widget.singleton_methods # => [:main]
Widget.send(:other) # => 103
p Widget.a # private method `a' called for Widget:Class (NoMethodError)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment