Adding methods to a ruby class

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.

Tags: ,

2 Responses to “Adding methods to a ruby class”

  1. Roy 12. Feb, 2010 at 00:32 #

    Hello,

    That looks like it would be very useful, but I’m not sure I follow. Do you have an example piece of code that you’ve used this example that you could share?

  2. R.I. Pienaar 12. Feb, 2010 at 00:36 #

    I am using it as above, an mcollective agent can either say:

    def foo_action
    end

    or use:

    action "foo" do
    end

    It’s just little tricks to make things look more like a DSL and less like a full on scary programming language

Leave a Reply