簡體   English   中英

精煉或猴子跳線4

[英]Rifinements or monkey patching rails 4

我正在使用rail4和ruby 2.0,我想在ActiveModel :: Errors中添加方法“ first_error” ,該方法應該在整個應用程序中都可用,因此遇到了以下兩種可能性:

  • 猴子補丁
  • 細化

僅通過創建初始化程序“ custom_model_error.rb”,我就成功實現了第一種方法

class ActiveModel::Errors
  def first_error
    if !self.first
      return nil
    end
    data = Hash.new
    data['error_code'] = '900'
    data['message'] = self.first.join(' ')
    return data
  end
end

但是,當我嘗試通過在lib目錄中定義一個模塊來實現第二種方法時:

  module RefineErrors
    refine ActiveModel::Errors do
      def first_error
        if !self.first
          return nil
        end
        data = Hash.new
        data['error_code'] = '900'
        data['message'] = self.first.join(' ')
        return data
      end
    end
  end

然后在ApplicationController中使用此模塊:

class ApplicationController < ActionController::API
   using RefineErrors

我得到錯誤的未定義方法'using'

現在我的問題是:

目前實施哪種最佳方法
通常不建議使用Monkey Patching,而完善是ruby 2.0的實驗功能

還想知道如何在rails4中使用改進來實現此目標嗎?

如果在這種情況下還有其他方法可以遵循,請同時提及。

如果您使用的是ruby 2.0,則需要使用支持完善功能的ruby補丁。在此處查看http://timelessrepo.com/refinements-in-ruby
此鏈接還共享猴子修補和優化的功能。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM