simo
simo

Reputation: 24558

Override initialize method of a gem?

I am trying to override initialize method of a gem as:

# rails_app_folder/lib/redis/unique/queue.rb

require "redis"

class Redis
  module Unique
    class Queue

      def initialize(name, redis_or_options = {})
        #Custom logic..
      end

    end
  end
end

However, when I create an new instance Redis::Unique::Queue.new the constructor in the gem folder is executed instead.

Any idea?

Upvotes: 2

Views: 1035

Answers (1)

Stefan
Stefan

Reputation: 114178

Instead of overwriting the method, you can move your custom implementation into a separate module and prepend it to the Queue class:

# config/initializers/queue_extension.rb

module QueueExtension
  def initialize(name, redis_or_options = {})
    # Custom logic

    super # <- as needed, invokes the original Redis::Unique::Queue#initialize
  end
end

Redis::Unique::Queue.prepend(QueueExtension)

Using prepend puts the code "in front" of the existing code.

If Redis::Unique::Queue is not available at that point, you might have to require it.

Upvotes: 1

Related Questions