DEV Community

andyreadpnw
andyreadpnw

Posted on

Rails Command Line Tools - Rake Re-seed Programmatically

As I was building out a project for my software engineering requirements, I found that my database seed design was likely to be a limiter on the functionality of my website. The project was a weather-based ecommerce store in Ruby on Rails and required that the seed file be called constantly in order to keep a weather API response up to date. Each time a user entered the site, the API would need to be called to assign the current weather to the user. Luckily, I found a solution with only a few lines of code that allowed a programmatic solve for my automated re-seed: embedding rake commands in the controller.

Executing seeds.rb from Rails application

1

I have some buttons to purge collections so it's easy to restore the website to pristine state during development/test, without even restarting the server.

How can I execute the content of seeds.rb inside a controller action ?

def purge
  if Rails.env.production?
    should_not_happen(severity: :armageddon)
  else
    # Well at least restore one

The way it works is to create a rake task that calls your external API, gets the data, and updates the database. Then schedule this task to run at the interval you require. One gem recommended is the whenever gem that can help run the jobs at certain intervals, however for my uses on only one system task: I simply coded the call directly in my controller. All things considered, it greatly simplified the design of my program and allowed real-time updating for the user. Great news!

Controller calling System Rake Command
Alt Text

Rake Command Task
Alt Text

Top comments (0)