I’m just blogging this because it took me ages to figure out, it seems so simple now but I guess that’s how it usually goes.
The problem I have is I want a plugin to be able to either make a method using the normal Ruby def foo or via some DSL’ish helpers.
class Foo<Base register_action(:name => "do_something", :description => "foo") def do_something_action end register_action(:name => "do_something_else", :description => "foo") do # body of the action here end end |
The above code should make me two methods – do_something_action and do_something_else_action – they should be identical to viewers from the outside. Here’s the base class that makes this happen correctly:
class Base def self.register_input(input, &block) name = input[:name] self.module_eval { define_method("#{name}_action", &block) } if block_given? end end |
It’s pretty simple, we’re just using define_method in the scope of the module and that does the rest.