问题
I'd like to know which providers have been loaded for use by the OmniAuth gem. I've tried this:
OmniAuth::Strategies.constants # a method provided by the standard lib Module class
# => [:Developer, :OAuth, :Twitter]
and this:
OmniAuth.strategies.inspect # a method provided by the OmniAuth class, but which has no documentation or comments around it.
# => [OmniAuth::Strategies::OAuth]
The answer I'd expect (or want) is [:Developer, :Twitter]
as in my test code I've only loaded twitter explicitly, and the developer provided is loaded by default.
(This is all so a different library can load the correct things for it to work, dependent on what OmniAuth is running.)
If there is a way and you know of it, please let me know. Otherwise I'll be pragmatic and knock OAuth out of the list from the first example.
Ruby is 1.9.3 and OmniAuth is v1.1.1
回答1:
OmniAuth::Strategies lists strategies available and registered. Not those that are in 'use'. If you dig through the code of OmniAuth builder, you will see that various strategies are passed onto Rack using use
as middleware in the provider block, which makes tracking the strategies harder. Another "pragmatic" approach is to monkey patch OmniAuth Builder and track the providers.
module OmniAuth
class Builder < ::Rack::Builder
def provider_patch(klass, *args, &block)
@@providers ||= []
@@providers << klass
old_provider(klass, *args, &block)
end
alias old_provider provider
alias provider provider_patch
class << self
def providers
@@providers
end
end
end
end
Include this patch before configuring your providers. Once all the providers have been loaded, OmniAuth::Builder.providers
will give you the array you want.
Even though Developer strategy is available, it is not loaded. It is only loaded if you specify
provider :developer
回答2:
Adding this here for Devise users, as I needed the same list as iain.
I tried using the accepted answer at the top of my devise initializer in a Rails project, but I got an error (@@providers was not defined).
After looking into the Devise source code, I used the following to get an array of symbols:
Devise.omniauth_configs.keys # => [:facebook, :twitter]
来源:https://stackoverflow.com/questions/13112430/find-loaded-providers-for-omniauth