I’m using the Sorcery library in a rails app. One of its modules is for external authentication, and I need to add a method to that module.
The existing code is here, I want to add the add_provider_to_user method from this patch.
So, I added a file to my lib/modules directory, which I’ve told rails to autoload. The file is called sorcery_extension.rb and it looks like this:
module Sorcery
module Controller
module Submodules
module External
module InstanceMethods
protected
# If user is logged, he can add all available providers into his account
def add_provider_to_user(provider)
provider_name = provider.to_sym
provider = Config.send(provider_name)
user_hash = provider.get_user_hash
config = user_class.sorcery_config
user = current_user.send(config.authentications_class.to_s.downcase.pluralize).build(config.provider_uid_attribute_name => user_hash[:uid], config.provider_attribute_name => provider)
user.save(:validate => false)
return user
end
end
end
end
end
end
This didn’t work. I get undefined method error in my controller (where calling the other sorcery methods works fine).
So, my basic understanding of ruby is you can add methods to an object or module at any time… I think I’ve copied the nesting of the modules correctly in the file. Do I need to name the module file something different? I’m not really sure how to do this kind of thing, so any help is much appreciated. Thanks!
Your file is never
required. You can double check this by typing in the console:The reason is that auloading only happens when a constant is unknown in which case Rails will try to autoload it from the different autoloaded paths.
You have to require your file explicitly (e.g. from a file in initializer) and things will work as expected.