HASH32 Engineering

Running a local Ruby Script in Heroku

December 10, 2017 | 4 Minute Read

Sometimes you require to run a local ruby script in your heroku server and get some result out of it directly in your local machine. There are a few options available for this sort of thing.

Running a local ruby script in Heroku console

Consider this scenario. You have a Rails app hosted in Heroku and need to find out the number of signups every day. You can always open up heroku console and run it by pasting the ActiveRecord count of users. But if you have a ruby script in your local you can pipe it to heroku console and get the output directly in your terminal.

# File ~/MyScripts/daily-signups.rb

user_count = User.where('created_at > ?', Date.current).count
user_emails = User.where('created_at > ?', Date.current).map(&:email)

puts "Total signups today #{user_count}"
puts "Signedup user emails #{user_emails.join(',')}"

You can run this in Heroku console as


cat ~/MyScripts/daily-signups.rb | heroku run console --app heroku-app-name --no-tty

This will give you a the required output directly in your terminal.

Running a ruby script to connect to the database

You can get the database credentials of your app using the Heroku cli


heroku pg:credentials

Then write a script to connect to the database as follows(assuming postgres):


# File ~/rails_app/scripts/user_signups.rb

require 'active_record'

ActiveRecord::Base.establish_connection(
  adapter: 'postgresql',
  encoding: 'unicode',
  database: 'abcd-databasename',
  host: 'ec2-123-123-123-123.compute-1.amazonaws.com',
  pool: 5,
  username: 'username',
  password: 'password'
)

results = ActiveRecord::Base.connection.execute(<<-EOQ)
  SELECT  name, email FROM users WHERE created_at >= CURRENT_DATE
EOQ

results.each do |row|
  puts row['name']
  puts row['email']
end

This can be run using the ruby interpreter as follows:

 bundle exec ruby scripts/report2.rb

Note (If you are running it in your rails project using bundle exec need not require explicit gem install active_record )

The second approach seems to be faster, when compared to the first.

Subscribe to our Newsletter

Get stories like the directly to your inbox once every two weeks.
Tips and tricks, news about tech tools, recent blog entries and exclusive email only stories.