Skip to content

Instantly share code, notes, and snippets.

@sorah

sorah/a.rb Secret

Last active December 20, 2015 14:49
Show Gist options
  • Save sorah/9219460908fa528eaa19 to your computer and use it in GitHub Desktop.
Save sorah/9219460908fa528eaa19 to your computer and use it in GitHub Desktop.
# Idea taken from https://github.com/sinatra/sinatra/blob/master/lib/sinatra/base.rb#L1525-L1535
class Foo
def run(&block)
generate_method("something_unique", &block).call :arg
end
private
def generate_method(name, &block)
self.class.class_eval do
define_method(name, &block)
method = instance_method(name)
remove_method(name)
method
end.bind(self)
end
# or
def generate_method(name, &block)
define_singleton_method(name, &block)
method = method(name)
self.singleton_class.instance_eval do
remove_method(name)
end
method
end
def blah
p :blah
end
end
Foo.new.run do |arg|
blah
p arg
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment