[英]Rails 3: How to add a method to the Gem model without changing the Gem source
version : Rails 3.2.22.2
I'm using the Impressionist gem to track user activity: https://github.com/charlotte-ruby/impressionist 我正在使用Impressionist gem来跟踪用户活动: https : //github.com/charlotte-ruby/impressionist
This gives me ActiveModel::MassAssignmentSecurity::Error
. 这给了我
ActiveModel::MassAssignmentSecurity::Error
。 I want to override the Impression
module from the gem to use attr_accessible
. 我想从gem覆盖
Impression
模块以使用attr_accessible
。
I tried 2 things: 我尝试了两件事:
1: Create an impression.rb
file under app/models
1:在
app/models
下创建一个impression.rb
文件
class Impression
def hello
"hello world"
end
end
In initializer/impression.rb
, 在
initializer/impression.rb
,
require 'impression'
when I try the following on console: 当我在控制台上尝试以下操作时:
a = Impression.first
a.hello
I get method not found error. 我得到方法未找到错误。
2: I added the code in the initializezs/impression.rb
file: 2:我将代码添加到
initializezs/impression.rb
文件中:
Impression.class_eval do
def hi
puts 'you got me!'
end
end
and I still got the same error as in point 1. 而且我仍然遇到与第1点相同的错误。
How can I effectively override the model from the gem? 如何有效地从gem覆盖模型?
I did the following modification to make my code work. 我做了以下修改以使我的代码正常工作。 Under initializers I create a file ->
initializer/my_monkey_patch.rb
with following code 在初始化程序下,我使用以下代码创建文件->
initializer/my_monkey_patch.rb
class Impression < ActiveRecord::Base
attr_accessible :impressionable_type, :impressionable_id, :controller_name, :action_name, :user_id, :request_hash, :session_hash, :ip_address, :referrer
def hello
"hello WORLD!"
end
end
Thank you @Mohammad Shahadat Hossain for all your help 谢谢@Mohammad Shahadat Hossain的所有帮助
I would prefer to go with 2 method. 我宁愿使用2方法。 But you have see if you method already in a class.
但是,您可以查看您是否已经在类中使用方法。 Then for overriding it you need to use in your
model/impression_decorator.rb
. 然后,为了覆盖它,您需要在
model/impression_decorator.rb
使用它。
Impression.class_eval do
attr_accessor :something
def hi
puts 'you got me! #{someting}'
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.