简体   繁体   中英

Rifinements or monkey patching rails 4

I am using rail4 and ruby 2.0, I want to add a method in that should be available throughout my application, So i came across following 2 possibilities : 中添加方法 ,该方法应该在整个应用程序中都可用,因此遇到了以下两种可能性:

  • Monkey Patch
  • Refinement

I has successfully implemented the first approach just by creating an initializer "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

But when i tried to implement the second approach by defining a module in lib directory:

  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

and then using this module in ApplicationController:

class ApplicationController < ActionController::API
   using RefineErrors

i get the error .

Now my questions are:

?
Monkey Patching is generally not recommended, and refinements is the experimental feature of ruby 2.0

Also want to know ? 吗?

If there is any other approach that should be followed in this scenario, please mention that also.

If you are using ruby 2.0, you need to use patch of ruby which support refinements.take a look at here http://timelessrepo.com/refinements-in-ruby
This links also share the power of monkey patching and refinements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM