[英]Rifinements or monkey patching rails 4
I am using rail4 and ruby 2.0, I want to add a method "first_error" in
ActiveModel::Errors that should be available throughout my application, So i came across following 2 possibilities :
我正在使用rail4和ruby 2.0,我想在ActiveModel :: Errors中添加方法
“ first_error” ,该方法应该在整个应用程序中都可用,因此遇到了以下两种可能性:
I has successfully implemented the first approach just by creating an initializer "custom_model_error.rb" 仅通过创建初始化程序“ 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: 但是,当我尝试通过在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
and then using this module in ApplicationController: 然后在ApplicationController中使用此模块:
class ApplicationController < ActionController::API
using RefineErrors
i get the error undefined method 'using' .
我得到错误的未定义方法'using' 。
Now my questions are: 现在我的问题是:
which is the best approach to implement at present ?
目前实施哪种最佳方法 ?
Monkey Patching is generally not recommended, and refinements is the experimental feature of ruby 2.0 通常不建议使用Monkey Patching,而完善是ruby 2.0的实验功能
Also want to know how to implement this using refinements in rails4 ?
还想知道如何在rails4中使用改进来实现此目标吗?
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 如果您使用的是ruby 2.0,则需要使用支持完善功能的ruby补丁。在此处查看http://timelessrepo.com/refinements-in-ruby
This links also share the power of monkey patching and refinements. 此链接还共享猴子修补和优化的功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.