ruby on rails 模型中的全局方法 [英] global methods in ruby on rails models
问题描述
我的所有模型中都有如下所示的方法:
I have methods in all of my models that look like this:
def formatted_start_date
start_date ? start_date.to_s(:date) : nil
end
我想要一些可以为每个模型中的每个日期时间字段自动编写这样的方法的东西,这样做的最佳方法是什么?
I would like to have something that automatically writes a method like this for each datetime field in each model, what's the best way to do this?
-C
推荐答案
我不得不回答这个问题,因为这是一个有趣的 Ruby 练习.
I just had to answer this, cos it's a fun Ruby excercise.
可以通过多种方式向类添加方法,但最简洁的方式之一是使用 Ruby 的一些反射和评估功能.
Adding methods to a class can be done many ways, but one of the neatest ways is to use some of the reflection and evaluation features of Ruby.
在您的 lib 文件夹中将此文件创建为 lib/date_methods.rb
Create this file in your lib folder as lib/date_methods.rb
module DateMethods
def self.included(klass)
# get all dates
# Loop through the class's column names
# then determine if each column is of the :date type.
fields = klass.column_names.select do |k|
klass.columns_hash[k].type == :date
end
# for each of the fields we'll use class_eval to
# define the methods.
fields.each do |field|
klass.class_eval <<-EOF
def formatted_#{field}
#{field} ? #{field}.to_s(:date) : nil
end
EOF
end
end
end
现在只需将它包含到任何需要它的模型中
Now just include it into any models that need it
class CourseSection < ActiveRecord::Base
include DateMethods
end
当包含在内时,该模块将查看任何日期列并为您生成 formatted_ 方法.
When included, the module will look at any date columns and generate the formatted_ methods for you.
了解 Ruby 的工作原理.其乐无穷.
Learn how this Ruby stuff works. It's a lot of fun.
也就是说,您必须问问自己是否有必要这样做.我不认为这是个人问题,但同样,写作很有趣.
That said, you have to ask yourself if this is necessary. I don't think it is personally, but again, it was fun to write.
-b-
这篇关于ruby on rails 模型中的全局方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!