Prateek Karkare
Prateek Karkare

Reputation: 173

Overriding a concern of a gem - Rails

I am trying to modify a gem (Devise token auth to be precise) to suit my needs. For that I want to override certain functions inside the concern SetUserByToken.

The problem is how do I override that?

I don't want to change the gem files. Is there an easy/standard way of doing that?

Upvotes: 4

Views: 1941

Answers (2)

max
max

Reputation: 102443

Bear in mind here that a "concern" in Rails is just a module with a few programmer conveniences from ActiveSupport::Concern.

When you include a module in a class the methods defined in the class itself will have priority over the included module.

module Greeter
  def hello
    "hello world"
  end
end

class LeetSpeaker
  include Greeter
  def hello 
    super.tr("e", "3").tr("o", "0")
  end
end

LeetSpeaker.new.hello # => "h3ll0 w0rld"

So you can quite simply redefine the needed methods in ApplicationController or even compose a module of your own of your own without monkey patching the library:

module Greeter
  extend ActiveSupport::Concern

  def hello
    "hello world"
  end

  class_methods do
     def foo
       "bar"
     end
  end
end

module BetterGreeter
  extend ActiveSupport::Concern

  def hello
    super.titlecase
  end

  # we can override class methods as well.
  class_methods do
     def foo
       "baz"
     end
  end
end

class Person
  include Greeter # the order of inclusion matters
  include BetterGreeter
end

Person.new.hello # => "Hello World"
Person.foo # => "baz"

See Monkey patching: the good, the bad and the ugly for a good explanation why it often is better to overlay your custom code on top of a framework or library rather than modifying a library component at runtime.

Upvotes: 5

Anthony E
Anthony E

Reputation: 11245

You can monkey patch concerns like any other module:

module DeviseTokenAuth::Concerns::SetUserByToken
  # Your code here
end

If you want to extend the behavior of an existing method, try using an around alias:

http://rubyquicktips.com/post/18427759343/around-alias

Upvotes: 0

Related Questions