Search code examples
ruby-on-railsrubytwitterrubygems

NameError: Uninitialized constant Twitter


When I try to run any command that uses the Twitter API in the ruby console, I get the error NameError: uninitialized constant Twitter.

I have named this twitterFeed.rb because I read that it should not be named twitter.rb. This file is placed in my config/initializers folder. I have ran bundle install already, and the line gem 'twitter', '~> 6.2' is in my gem file.

require 'rubygems'
require 'bundler/setup'

require 'twitter'
require 'json'

client = Twitter::REST::Client.new do |config|
 config.consumer_key = ENV['TWITTER_CONSUMER_KEY']
 config.consumer_secret = ENV['TWITTER_CONSUMER_SECRET']
 config.access_token = ENV['TWITTER_ACCESS_TOKEN']
 config.access_token_secret = ENV['TWITTER_ACCESS_TOKEN_SECRET']
end

Solution

  • It looks like you're trying to use irb instead of the Rails console to run your code. When you run through irb (or pry), you aren't actually loading the Rails environment, so none of the gems will be available. You can manually require them, but you still won't have access to the Rails environment.

    What you want to do instead is use rails console (or rails c for short).

    For example with irb, Twitter isn't loaded:

    rails_dir » irb
    2.2.4 :001 > Twitter
    NameError: uninitialized constant Twitter
        from (irb):1
        from /Users/bbugh/.rvm/rubies/ruby-2.2.4/bin/irb:11:in `<top (required)>'
    

    With rails c, it works just fine:

    rails_dir » rails c
    Loading development environment (Rails 5.0.1)
    2.2.4 :001 > Twitter
    => Twitter
    

    You can take all of those requires out of your initializer - Rails will require the gems automatically by that point. You just need to use rails console when you're doing console work with Rails.