Siva
Siva

Reputation: 8058

Rails - How to override method in Module which is inside Class

I want to override marshal method in ActiveRecord but not sure how to do for a method inside module inside a Class

module ActiveRecord
 class SessionStore < ActionDispatch::Session::AbstractStore
   module ClassMethods
      def marshal(data)
        ::Base64.encode64(Marshal.dump(data)) if data
      end
   end
 end
end

I've tried this on config/initializers/active_record.rb

ActiveRecord::SessionStore.class_eval do
 ClassMethods.module_eval do
   def marshal(data)
      # Code
   end
 end
end

But it throws an error

config/initializers/active_record.rb:2:in `block in <top (required)>': uninitialized constant ClassMethods (NameError)

EDIT

I am trying to override from config/initializers/active_record.rb, dont wanna edit gem file

Upvotes: 0

Views: 1599

Answers (2)

BroiSatse
BroiSatse

Reputation: 44675

You can do this simpler using:

ActiveRecord::SessionStore::ClassMethods.module_eval do
  def marshal(data)
    // code
  end
end

or even simpler

module ActiveRecord::SessionStore::ClassMethods
  def marshal(data)
    // code
  end
end

Upvotes: 2

Edgars Jekabsons
Edgars Jekabsons

Reputation: 2853

Have You tried simply redefining?

module ActiveRecord
  class SessionStore
    module ClassMethods
      def marshal(data)
        # Code
      end
    end
  end
end

Upvotes: 0

Related Questions