avinashbot / redd

Redd is a batteries-included API wrapper for reddit.
MIT License
186 stars 76 forks source link

NoMethodError (undefined method `access_token' for #<Redd::Models::Access:0x00007fb75d2f95b0>): #98

Open itsmichaelwang opened 4 years ago

itsmichaelwang commented 4 years ago

If you're getting this error, it's possibly because of this line in the library (Redd::APIClient):

def connection
  super.auth("Bearer #{@access.access_token}")
end

Basically it tries to access this field access_token on @access, which is of the type Redd::Models::Access. That field doesn't exist so it goes to the superclass, Redd::Models::BasicModel, which has the fallback method:

def method_missing(method_name, *args, &block)
        return get_attribute(method_name) if @attributes.key?(method_name)
        # @itsmichaelwang - add this line here
        return get_attribute(method_name.to_s) if @attributes.key?(method_name.to_s)
        return get_attribute(depredicate(method_name)) if @attributes.key?(depredicate(method_name))
        super
      end

The problem is that method_name is a symbol (and in this case, it's :access_token), but if you were to inspect the attributes object here you would see that acess_token is actually a string key. So it's a simple case of mixing up our strings and symbols.

tl;dr: If you insert that line I commented in above, your library should work.

I don't think this is the correct way to solve it. I'm pretty sure the access token is not being correctly set with a symbol key somewhere, but if it works it works. After this, I was able to get Redd working (Redd + Rails 5/no sinatra, using the Middleware).

If anyone is curious, here's my application.rb for middleware without Sinatra (stuff in angle brackets was removed for privacy purposes):

module Blog
  class Application < Rails::Application
    # Initialize configuration defaults for originally generated Rails version.
    config.load_defaults 6.0

    # Settings in config/environments/* take precedence over those specified here.
    # Application configuration can go into files in config/initializers
    # -- all .rb files in that directory are automatically loaded after loading
    # the framework and any gems in your application.
    #
    if Rails.env.production?
      config.middleware.use Redd::Middleware, {
        user_agent: 'My Reddit App',
        client_id: <client id>,
        secret: ENV['REDDIT_OAUTH_SECRET'],
        redirect_uri: <url>,
        scope: ['submit']
      }
    else
      config.middleware.use Redd::Middleware, {
        user_agent: 'My Reddit App',
        client_id: <client id>,
        secret: <secret>,
        redirect_uri: <url>,
        scope: ['identity, submit']
      }
    end
  end
end
pooriajr commented 3 years ago

I'm getting this issue using Redd in Rails. I don't really know where to make the change you mentioned though. Am I supposed to fork the gem and update part of it?