Accessing ENV variables in rake task

I’m using foreman along with a .env file for storing all my config vars. However, whenever I try to access them in a rake task they always come up blank. Here’s a basic example of what I’m trying to do:

task :send_to_twitter => :environment do                                                                                                                                   
                                                                                                                                                                          
   @twit = Twitter::REST::Client.new do |config|                                                                                                                            
     config.consumer_key         = ENV['TWITTER_KEY']                                                                                                                     
     config.consumer_secret      = ENV['TWITTER_SECRET']                                                                                            
     config.access_token         = ENV['TWITTER_ACCESS_TOKEN']                                                                                   
     config.access_token_secret  = ENV['TWITTER_SECRET_ACCESS_TOKEN']                                                                                           
   end

   @twit.update "I'm tweeting via a rake task!"

end

None of the ENV variables above work, and I imagine I’m going to run into the same problem when I deploy to Heroku. Any ideas on how I can use the ENV vars in this rake task?

Thanks!

Foreman uses [dotenv] (GitHub - bkeepers/dotenv: A Ruby gem to load environment variables from `.env`.) under the covers. From that readme:

To ensure .env is loaded in rake, load the tasks:

require 'dotenv/tasks'

task :mytask => :dotenv do
    # things that require .env
end

Thank you @derekprior ! To get it working I added the dotenv-rails gem. I didn’t have to require 'dotenv/tasks' in the rake task as a result.

To get it working on Heroku I couldn’t leave the gem in a :test or :development group. From what I understand Foreman has dotenv built in but unless I added the dotenv-rails gem to my Gemfile, my rake task wouldn’t work?

My rake task also ended up looking like this since I also wanted to access my models:

task :mytask => [:environment, :dotenv] do
      # things that require .env
      # things that require models
end