views:

32

answers:

1

Hi folks, today, i am defining a set of variables in a hash that I use in various functions all over the model and the controller.

From the code below, you see that I am defining functions like get_stats, get_fans to target the exact variable.

My question is, would it be possible to define just one function?

NOW:

REQ={:USER_STATS_IN_NETWORK =>1 ,
     :FANS_IN_NETWORK => 2}


USER_STATS_IN_NETWORK_TYPE_ID =REQ[:USER_STATS_IN_NETWORK]
get_stats= some_function(params,USER_STATS_IN_NETWORK_TYPE_ID)


FANS_IN_NETWORK_TYPE_ID = REQ=[:FANS_IN_NETWORK_TYPE_ID]
get_fans= some_function(params,FANS_IN_NETWORK_TYPE_ID)

repeat for 10-over times...

** WANT TO ACHIEVE:**

REQ={:USER_STATS_IN_NETWORK =>1 ,
     :FANS_IN_NETWORK => 2}

#get_* => return some_function(:*) , without defining all of them explicitly
#example: get_user_stats => returns some_function(:USER_STATS_IN_NETWORK)
+2  A: 

You may try something like this:

REQ.keys.each do |key|
  self.class.send(:define_method, "get_#{key.to_s.sub(/_IN_NETWORK$/, '').downcase}") do
    some_function(key)
  end
end
lest
Thanks! In this case, what does the "self" in L2 refer to?
ming yeow
It refers to current object. I call define_method on class of current object.
lest