Rails 模型上的动态方法
我意识到这不一定是最明智的方法,但现在我的好奇心很活跃,我很好奇如何做到这一点。
我在 Rails 项目中有一个模型。我们将其称为“交易”。每个 ActiveRecord 和所有这些很酷的东西都在数据库中定义了诸如 UPDATED_AT 之类的列,这些列成为 Deal 上的方法: deal.updated_at => '04/19/1966 3:15am'
假设我想要有一些方法来告诉我星期几,而不是整个日期和时间。我意识到 DateTime 类上有方法,所以我可以这样做
deal.updated_at.day_of_week => 'Monday' (*)
,但是如果我只想
deal.updated_day => 'Monday'
写在 deal.rb 中
def update_day
self.updated_at.day_of_week
end
怎么办?
但是,如果我希望它始终具有可用于添加到模型中的任何日期列的方法,该怎么办?
我在那里看到了define_method(一些在StackOverflow上)。所以我明白了。但我想在 ActiveRecord 发挥其魔力之后立即调用它,对吧?因此,如果我的 Deal 模型有updated_at、created_at、offered_at 和suitable_at,我会希望为每一个都匹配方法。更重要的是,如果另一个开发人员添加了一个名为 Cammed_at 的列,我希望与 Cammed_at 方法一起创建 Cammed_day 。
我该怎么做呢?
谢谢。
(*) 呃,或者类似的事情,我总是查看那个电话。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我想像下面这样的东西应该可以解决问题。在您的模型中:
但这意味着每一列都有一个有效的
day_of_week
方法...好吧,我想您明白了。请随时询问详情
I guess something like the following should do the trick. In your model:
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