我的所有模型中都有如下所示的方法:
def formatted_start_date
start_date ? start_date.to_s(:date) : nil
end
我想要为每个模型中的每个日期时间字段自动编写这样的方法,最好的方法是什么?
-C
最佳答案
我只需要回答这个问题,因为这是一个有趣的 Ruby 练习。
向类中添加方法有很多种方法,但最巧妙的方法之一是使用 Ruby 的一些反射和求值特性。
在您的 lib 文件夹中将此文件创建为 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
现在只需将它包含在任何需要它的模型中
class CourseSection < ActiveRecord::Base
include DateMethods
end
包含后,该模块将查看任何日期列并为您生成 formatted_ 方法。
了解这个 Ruby 的东西是如何工作的。其乐无穷。
也就是说,你必须问问自己这是否有必要。我不认为这是个人的,但同样,写起来很有趣。
-b-
关于ruby-on-rails - ruby on rails 模型中的全局方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/863613/