Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic Methods on a Rails Model

I realize this is not necessarily the smartest way to do this, but now my curiosity is active and I am curious how to do it.

I have a model in the Rails project. We'll call it Deal. Per ActiveRecord and all that cool stuff there are columns defined in the database like UPDATED_AT and those become methods on Deal: deal.updated_at => '04/19/1966 3:15am'

Say I wanted to instead have methods that told me the day of the week rather than the whole date and time thing. I realize there are methods ON the DateTime class so I can do

  deal.updated_at.day_of_week => 'Monday' (*)

but what if I just wanted

  deal.updated_day => 'Monday'

I can write in deal.rb

  def update_day
    self.updated_at.day_of_week
  end

Got it.

But what if I wanted it to ALWAYS have the method available for ANY date column that was added to the model?

I saw define_method out there (some here on StackOverflow). So I understand that. But I would want to call it right after ActiveRecord did its magic, right? So if my Deal model had updated_at, created_at, offered_at and lawsuit_at I would want matching methods for each one. More importantly, if another developer came and added a column called scammed_at I would want scammed_day created along with the scammed_at method.

How would I do that?

Thanks.

(*) Uh, or something like that, I always look that call up.

like image 872
Colin Summers Avatar asked May 30 '11 17:05

Colin Summers


1 Answers

I guess something like the following should do the trick. In your model:

# looping through all model's columns
self.columns.each do |column|
  #if column's name ends with "_at"
  if column.name =~ /_at$/
    #create method like "udpated_day" 
    define_method "#{column.name[0..-4]}_day" do
      self.send(column.name).day_of_week
    end
  end
end

But it implies every column has a valid day_of_week method...

Well you get the idea I think. Don't hesitate to ask for details

like image 106
apneadiving Avatar answered Oct 03 '22 23:10

apneadiving