www.devco.net by r.i.pienaar

5Feb/102

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.

About R.I. Pienaar

Systems Administrator, Consultant, Linux Guy, Automator, Ruby Coder
Tagged as: , Leave a comment
Comments (2) Trackbacks (0)
  1. 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. 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 comment


No trackbacks yet.