Dynamic Methods for the Rails Model

I understand that this is not the most reasonable way to do this, but now my curiosity is active, and I am curious how to do it.

I have a model in a Rails project. We will call it the Deal. ActiveRecord and all these cool things have columns defined in the database, such as UPDATED_AT, and those become Deal methods: deal.updated_at => '04 / 19/1966 3:15 am '

Let's say I wanted to use methods instead that told me the day of the week, not the whole date and time. I understand that there are methods in 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 ALWAYS to have a method available for the ANY date column that was added to the model?

I saw define_method there (some here in StackOverflow). Therefore, I understand that. But I would like to call it right after ActiveRecord did its magic, right? So if my transaction model updated_at, created_at, suggested_at and lawuit_at, I would like the corresponding methods for each of them. More importantly, if another developer came along and added the scammed_at column, I would like scammed_day to be created along with the scammed_at method.

How can I do it?

Thanks.

(*) Uh, or something like that, I always watch what I call.

+6
source share
1 answer

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

 # looping through all model columns self.columns.each do |column| #if column 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 this means that each column has a valid day_of_week method ...

Well, you understand what I think. Feel free to ask for details.

+8
source

Source: https://habr.com/ru/post/889397/


All Articles