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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With