Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 455
KavitaC Avatar asked Dec 11 '25 03:12

KavitaC


1 Answers

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

like image 130
KavitaC Avatar answered Dec 13 '25 15:12

KavitaC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!