views:

27

answers:

2

I am trying to define a set of functions where I can pass in given params.

for example, how do i do the following?

>> get_1_type("xxx")

V4_RELATIONSHIP_TYPES=[1=>2,3=>4]

V4_RELATIONSHIP_TYPES.keys.each do |key|
 self.class.send(:define_method, "get_#{key}_type".downcase) do
  return GuidInfo.get_or_new(PARAMS, V4_RELATIONSHIP_TYPES[key])
 end
end

# i can call -> get_1_type("xxx") , and get the function called
+1  A: 

I'm not sure why you would create a method that way instead of just opening up the class again and inserting your method, but you could use class_eval instead:

self.class.class_eval %Q{
  def get_#{key.downcase}_type(...)
    ...
  end
}
Daniel Vandersluis
+2  A: 

Try this:

V4_RELATIONSHIP_TYPES.keys.each do |key|
 self.class.send(:define_method, "get_#{key}_type".downcase) do |param|
  # use param
  return GuidInfo.get_or_new(PARAMS, V4_RELATIONSHIP_TYPES[key])
 end
end

Now you can invoke the method with a parameter:

get_1_type("xxx")

Edit 1

Some links about Ruby blocks:

Start with this one

Link 1

Link 2

KandadaBoggu
thanks, this is great! Do you mind explaining what this is really doing? In particular, I do not get how the block works
ming yeow
Block is used as the method body and the block parameters are used as the method parameters.
KandadaBoggu
thanks a lot! Still getting my head around block, yield, etc. How did you become proficient in it?
ming yeow
Google, Rails source code. I have updated my answer with few links to articles about Ruby blocks.
KandadaBoggu