Max
Max

Reputation: 15955

Overwriting methods in a module

I am using a gem in my rails app, and there is a method that I would like to override. The gam is authlogic, and the specific method I was to override is find_by_smart_case_login_field(login).

I made a file in lib/modules with the following code:

# lib/modules/login.rb
module Authlogic
  module ActsAsAuthentic
    module Login
      module Config
        def find_by_smart_case_login_field(login)
          login = login.downcase unless validates_uniqueness_of_login_field_options[:case_sensitive] 

          if login_field
            where({ login_field.to_sym => login })
          else
            where({ email_field.to_sym => login })
          end
        end
      end
    end
  end
end

But this didn't do anything. Does anyone know how to overwrite the above method?

Upvotes: 0

Views: 94

Answers (2)

Billy Chan
Billy Chan

Reputation: 24815

Well, you are monkey patching a gem. Not bad, just don't abuse it:)

Two things you need to do before making your monkey patching works.

  1. Add /lib to auto load path otherwise Rails don't know it.

    In config/application.rb, find the autoload_path line, change it to

    config.autoload_paths += %W(#{config.root}/extras #{config.root}/lib)
    
  2. Require your custom module at app loading.

    In config/initializers, add a custom file say application.rb, then add the following line

    require 'modules/login.rb'
    # Pay attention: No "lib/" before the file path
    

Now, profit!

As to module path, it doesn't matter as long as your module nesting is correct in the file.

Upvotes: 1

Jason Swett
Jason Swett

Reputation: 45074

I'm going out on a limb here, but my guess would be that you'd have to name the file something like

lib/authlogic/acts_as_authentic/login/config.rb

In other words, I believe the path has to map to the module structure.

Upvotes: 0

Related Questions