加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – ruby?? on rails模型的全局方法

发布时间:2020-12-16 21:17:44 所属栏目:百科 来源:网络整理
导读:我的所有模型中的方法都是这样的: def formatted_start_date start_date ? start_date.to_s(:date) : nilend 我希望能为每个模型中的每个日期时间字段自动编写这样的方法,这样做的最佳方法是什么? -C 解决方法 我只需回答这个问题,因为这是一个有趣的Ruby
我的所有模型中的方法都是这样的:
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-

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读