Home Time-based conditionals for ROR
Reply: 1

Time-based conditionals for ROR

user3133353
1#
user3133353 Published in 2017-11-29 23:13:32Z

I'm running a ROR Database-driven website operating out of C9 IDE; It's a website where users submit text through an html form to collaborate on a story, one sentence at a time.

What I'm Trying to do: I need to figure out the syntax necessary to have the database purge itself every thirty days. Broadly, I need to create an if-then statement that can run independently of either user input or my input in the background, meaning that I need a script that can be in the background whenever the server is active. Input is appreciated!

UPDATE: I understand that there is a possible duplicate of this question and I want to clarify how this is different; that question is outdated because Heroku has since deprecated the framework being used, and I also don't really want to use Heroku.

XP84
2#
XP84 Reply to 2017-11-30 01:53:44Z

How I'd approach this

2 components:

a. Rake task to do the purge.

# lib/tasks/purge.rb
desc "Purges the database"
task purge_db: :environment do
  # do your purge, e.g.
  puts "Purging at #{Time.current}..."
  Sentences.delete_all
  Stories.delete_all
  puts "Success."
end

b. cron job to run rake task

Log into the server where your Rails app runs in production. If you're not familiar with unix text editors such as emacs or vi, I'd recommend using nano for this task.

EDITOR=nano crontab -e

You'll be editing a file. I like to put a header at the top - this is useful for keeping straight which columns to fill in. Lines which start with # are ignored as comments. Just add a line like this. This will run at 5:00 AM on the 1st of the month:

   0     5     1     *    *   cd /path/to/myapp && rake purge_db >> /path/to/myapp/log/purge_log.txt 2>&1

If you're using nano, just hit ^O and to save, ^X to exit.

You'll see I've redirected output to an ad-hoc log. (you'd just see whatever your rake task outputs).

To make sure your task works (that you are using the right ruby environment variables, permissions, etc), you probably want to take out all the destructive statements, maybe add a harmless statement (e.g. puts Story.first.name) and set your crontab to run every minute and see if lines start appearing in the log.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.324058 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO