[英]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.我在 Rails 项目中有一个 model。 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'
根据 ActiveRecord 和所有很酷的东西,在数据库中定义了像 UPDATED_AT 这样的列,这些列成为 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
我意识到 DateTime class 上有一些方法,所以我可以做
deal.updated_at.day_of_week => 'Monday' (*)
but what if I just wanted但如果我只是想要
deal.updated_day => 'Monday'
I can write in deal.rb我可以写在 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?但是,如果我希望它始终具有可用于添加到 model 的任何日期列的方法怎么办?
I saw define_method out there (some here on StackOverflow).我在那里看到了define_method(StackOverflow 上有一些)。 So I understand that.
所以我明白这一点。 But I would want to call it right after ActiveRecord did its magic, right?
但我想在 ActiveRecord 发挥它的魔力之后立即调用它,对吧? So if my Deal model had updated_at, created_at, offered_at and lawsuit_at I would want matching methods for each one.
因此,如果我的 Deal model 有 update_at、created_at、offered_at 和诉讼_at,我希望每一个都匹配方法。 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.
更重要的是,如果另一个开发人员来添加一个名为scammed_at 的列,我希望scammed_day 与scammed_at 方法一起创建。
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:
在您的 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...但这意味着每一列都有一个有效的
day_of_week
方法......
Well you get the idea I think.好吧,你明白我的想法。 Don't hesitate to ask for details
不要犹豫,询问详情
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.