If you're overriding a class provided by a gem, you will need to manually require your version to get your changes included. This is usually done in an initializer.
Reopen Impression Class from Impressionist Gem in Rails 4
-
30-06-2022 - |
Question
I'm trying to modify the Impressionist gem class "Impression" to no avail.
I've tried the following:
class Impression
def hello
"world"
end
end
Impression.class_eval do
end
both in: /app/models/impression.rb and /lib/impression.rb (with correct configuration to include this folder)
What am I doing wrong? I'm using Rails 4. Ideally, I'd like to add an active record association and add some helper methods.
Solution
OTHER TIPS
i assume that you are talking about this gem: https://github.com/charlotte-ruby/impressionist and want to change the model class Impression.
from what i can see it is supposed to be a rails engine.
rails engines use to be namespaced, a stack-trace might have revealed this.
did you try this?
# app/extensions/impressionist/impression.rb
module Impressionist
class Impression
def hello
"world"
end
end
end
you could also try putting your code in an initializer, because it might also be a load order problem.
Try this:
require Impressionist::Engine.root.join('lib/impressionist/models/active_record/impression')
class Impression
def hello
"world"
end
end
Extending a model class with your own methods should be done using a concern. Try putting this in a file in your lib
folder and require it in an initializer:
require Impressionist::Engine.root.join('lib/impressionist/models/active_record/impression')
module ImpressionExtensions
extend ActiveSupport::Concern
def some_instance_method
# do some stuff
end
module ClassMethods
def some_class_method
# do some stuff
end
end
end
Impression.send(:include, ImpressionExtensions)
Adding methods to any model should be done in a similar manner. The way Impressionist works is a bit different, in that it first defines the Impression class as a regular, standalone class, before overriding it and making it a model.