简体   繁体   中英

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

This gives me ActiveModel::MassAssignmentSecurity::Error . I want to override the Impression module from the gem to use attr_accessible .

I tried 2 things:

1: Create an impression.rb file under app/models

class Impression
  def hello
    "hello world"
  end
end

In 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:

Impression.class_eval do
    def hi
        puts 'you got me!'
    end
end

and I still got the same error as in point 1.

How can I effectively override the model from the 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

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

I would prefer to go with 2 method. 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 .

Impression.class_eval do
  attr_accessor  :something

  def hi
    puts 'you got me! #{someting}'
  end
end

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