开发者

Getting the name of Ruby method for a literal hash query

开发者 https://www.devze.com 2023-03-11 03:09 出处:网络
In a rails application, I have a number of attributes for a model called Record. I want to design a method that when called on an attribute, returns the name of the attribute (which is essentially a m

In a rails application, I have a number of attributes for a model called Record. I want to design a method that when called on an attribute, returns the name of the attribute (which is essentially a method on the Record object). This name is then passed to an Hash, which returns a number (for the sake of this example, say the number is a percentage which is then multiplied by the original attribute value to get a new value).

For example, say my Record has four attributes: teachers, students, principals, and parents. The method would then look like the following:

def name
  **something here**
end

and the corresponding new_value method and PRECENTAGE hash would look like this:

def new_value
  self * PERCENTAGE[self.name]
end

PERCENTAGE = {
  "teachers"   => 0.40,
  "students"   => 0.53,
  "principals" => 0.21,
  "parents"    => 0.87
}
开发者_开发问答

Then, to execute this whole thing, I would do Record.students.new_value, which would return new number of students according to the percentage obtained in the hash.

I know that to get the name of a method that is currently executing, you can do something like this: (found on http://ryat.la/7RDk)

def this_method
  __method__
end

but that won't work for me, because I need the name of the previously executed method.

If you have any suggestions as to an alternative approach to accomplishing my goal, I'd be happy to try something else.


Ryan, I'm struggling to understand your question, but I think this is what you want, for record.teachers_percent, for example:

["teachers", "students", "principals", "parents"].each do |attrib|
  Record.class_eval <<-RUBY
    def #{attrib}_percent
      #{attrib} * PERCENTAGE[#{attrib.inspect}]
    end
  RUBY
end

Although this is probably a cleaner solution, giving record.percent(:teachers) or record.percent("teachers"):

class Record
  def percent(attrib)
    self.send(attrib) * PERCENTAGE[attrib.to_s]
  end
end
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号