Rails 扩展 ActiveRecord::Base [英] Rails extending ActiveRecord::Base

查看:22
本文介绍了Rails 扩展 ActiveRecord::Base的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了一些关于如何扩展 ActiveRecord:Base 类的文章,这样我的模型就会有一些特殊的方法.扩展它的简单方法是什么(分步教程)?

I've done some reading about how to extend ActiveRecord:Base class so my models would have some special methods. What is the easy way to extend it (step by step tutorial)?

推荐答案

有几种方法:

阅读ActiveSupport::Concern 文档了解更多详情.

Read the ActiveSupport::Concern documentation for more details.

lib目录下创建一个名为active_record_extension.rb的文件.

Create a file called active_record_extension.rb in the lib directory.

require 'active_support/concern'

module ActiveRecordExtension

  extend ActiveSupport::Concern

  # add your instance methods here
  def foo
     "foo"
  end

  # add your static(class) methods here
  class_methods do
    #E.g: Order.top_ten        
    def top_ten
      limit(10)
    end
  end
end

# include the extension 
ActiveRecord::Base.send(:include, ActiveRecordExtension)

config/initializers 目录中创建一个名为 extensions.rb 的文件,并将以下行添加到文件中:

Create a file in the config/initializers directory called extensions.rb and add the following line to the file:

require "active_record_extension"

继承(首选)

请参阅 Toby 的答案.

config/initializers 目录中创建一个名为 active_record_monkey_patch.rb 的文件.

Create a file in the config/initializers directory called active_record_monkey_patch.rb.

class ActiveRecord::Base     
  #instance method, E.g: Order.new.foo       
  def foo
   "foo"
  end

  #class method, E.g: Order.top_ten        
  def self.top_ten
    limit(10)
  end
end

Jamie Zawinski 关于正则表达式的名言可以重新利用来说明与猴子补丁相关的问题.

The famous quote about Regular expressions by Jamie Zawinski can be re-purposed to illustrate the problems associated with monkey-patching.

有些人在遇到问题时会想我知道,我会用猴子修补."现在他们有两个问题.

Some people, when confronted with a problem, think "I know, I'll use monkey patching." Now they have two problems.

Monkey 修补既简单又快捷.但是,节省的时间和精力总是被提取回来在未来的某个时候;与复利.这些天我限制了猴子修补以在 Rails 控制台中快速构建解决方案原型.

Monkey patching is easy and quick. But, the time and effort saved is always extracted back sometime in the future; with compound interest. These days I limit monkey patching to quickly prototype a solution in the rails console.

这篇关于Rails 扩展 ActiveRecord::Base的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆