红宝石全局方法上轨型号 [英] 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锻炼; Tibial。
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.
了解如何红宝石东西的作品。这是一个很大的乐趣。
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 -
这篇关于红宝石全局方法上轨型号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!