Run ruby on rails on upstart - ruby-on-rails

I'm folowing this link to put ruby on rails start automatically.
But I cant understand its ruby code
#!/usr/bin/env ruby
require File.expand_path("../../config/environment", __FILE__) #1.what is this path?
STDOUT.sync = true
Stalker::job 'user.fetch_details' do |args| #2.what is this user?
begin
user = User.find(args['id']) #3.what is this id?
user.fetch_user_details!
rescue ActiveRecord::RecordNotFound # too fast
Rails.logger.warn "Unable to find user ##{args['id']} - suspect too fast, requeuing"
Stalker.enqueue('user.fetch_details', :id => args['id'])
end
end
jobs = ARGV.shift.split(',') rescue nil
Stalker.work jobs
and conf file code in /etc/init/
description "TweetedLinks Ruby Worker"
# automatically start
start on filesystem
# working directory
chdir /var/www/TweetedLinks/current #4.should I change this to my own dir?ie home/usr/Trail/test-app
# command to run, with Bundler support!
env RAILS_ENV=production
exec bundle exec ruby script/worker.rb >> log/worker.log #5.do i need to create this worker.log? and this script folder can be put anywhere?
respawn
I have my rails app under home/usr/Trail/test-app
I have create a script folder under home/usr/script
I have my rvm generated under home/usr/.rvm/wrapper/test-app
How to modify this code according to my situation.
and the 5 question in code comments I also very confuse.
Thanks in advance!have been stuck for month!

The easiest way would be to use foreman gem that can export Procfile to upstart, see http://ddollar.github.io/foreman/#UPSTART-EXPORT

Related

Rails: Where to put script/function that runs only when starting server?

I am using the Predictor gem for a recommendation system. I want to write a script to initialize the recommender when running rails server. If I put the script into the initializers/dirctory, it will also be run whenever rake is executed.
Is there a way to add scripts are executed only when running rails server?
Thought it is not recommended, you could update the file bin/rails:
#!/usr/bin/env ruby
puts "Write your custom code here"
APP_PATH = File.expand_path('../../config/application', __FILE__)
require_relative '../config/boot'
require 'rails/commands'
This runs whenever rails s, rails c or any rails command is called.

How can I use clockwork to input data every hour?

My environment is Macbook OSX 10.7 Lion with Ruby 2.0 and Rails 4.
I am new to RoR. I built a website with one column database using a scaffold.
It's just a little website about weather.
I want to input degrees to database every hour.
And I found the gem clockwork, but I have no idea how to use it with my project.
I wrote clock.rb and put it in my project file and ran rails s but nothing happened.
Here is myproject/clock.rb
myproject/clock.rb
require 'clockwork'
module Clockwork
handler do |job|
puts "Running #{job}"
every(1 hours, ''){
Mydata.create(:degree => input_data)
}
end
What should I do with it or where should I put the file?
They say that I need to use $ clockwork clock.rb, but when I run rails s, there's no way to use that...
Thanks a lot.
As stated in the official docs you need a couple of things.
setup the clock file, I've set it in app/clock.rb
require 'clockwork'
module Clockwork
handler do |job|
case job
when 'weather.input_degree'
Mydata.create degree: input_data
# when 'some_other_task'
# ...
else
puts "Couldn't find your job!"
end
end
every(1.hour, 'weather.input_degree') # the string indicates an arbitrary job name
# every(20.seconds, 'weather.some_other_task')
end
The starting process. The key is to use something like Foreman
$ gem install foreman
Create a file named Procfile in root of your app:
web: bundle exec rails -s
clock: bundle exec clockwork app/clock.rb
# any_other_service_you_want: bash script here
start your server
$ foreman start
Add to Gemfile ­
gem 'clockwork'
after adding upper listed gem in gemfile, use bundle install to add this gem into project.
Example ­
Create a file clock.rb under /lib directory
clock.rb
require File.expand_path('../../config/boot', __FILE__)
require File.expand_path('../../config/environment', __FILE__)
require 'clockwork'
include Clockwork
module Clockwork
## Here Student is a domain class, having a method insertRecord to
## insert a record in DB
every(20.seconds, 'job ­ Inserting Record in DB') { Student.insertRecord }
end
Command to Run the clockword
bundle exec clockwork lib/clock.rb
This code needs stay outside of handler block:
every(1.hour, ''){ Mydata.create(:degree => input_data) }
You can execute the clock like that:
bundle exec clockwork clock.rb
You can make use of Cron. Write a rake task and call the rake task from the Cron for repeating processes.
Example (Add this to cron to run the task every hour):
0 * * * * cd /home/projectdir;rake do:task

Gem stalker on production

I'm using Stalker to interact with beanstalkd on a production server. My jobs file looks like this:
gem 'stalker'
# config/jobs.rb with Rails
RAILS_ENV = ENV["RAILS_ENV"] || "development"
require File.expand_path("../environment", __FILE__)
job "mapeamento_paciente.importar" do |args|
mapeamento = Mapeamento::Paciente.find(args['id'])
importador = ImportadorPaciente.new(mapeamento)
importador.importar!
end
I'm trying to start stalker by issuing the command:
bundle exec stalk config/jobs.rb RAILS_ENV=production
But on loading the environment file, Rails tries to access the development database, instead of production, issuing an error. Does anybody knows how to solve this issue!?
Thanks!
RAILS_ENV=production bundle exec stalk config/jobs.rb

rake task via cron problem loading rubygems

I have managed to get a cron job to run a rake task by doing the following:
cd /home/myusername/approotlocation/ && /usr/bin/rake sendnewsletter RAILS_ENV=development
i have checked with which ruby and which rake to make sure the paths are correct (from bash)
the job looks like it wants to run as i get the following email from the cron daemon when it completes
Missing these required gems:
chronic
whenever
searchlogic
adzap-ar_mailer
twitter
gdata
bitly
ruby-recaptcha
You're running:
ruby 1.8.7.22 at /usr/bin/ruby
rubygems 1.3.5 at /home/myusername/gems, /usr/lib/ruby/gems/1.8
Run `rake gems:install` to install the missing gems.
(in /home/myusername/approotlocation)
my custom rake file within lib/tasks is as follows:
task :sendnewsletter => :environment do
require 'rubygems'
require 'chronic'
require 'whenever'
require 'searchlogic'
require 'adzap-ar_mailer'
require 'twitter'
require 'gdata'
require 'bitly'
require 'ruby-recaptcha'
#recipients = Subscription.all(:conditions => {:active => true})
for user in #recipients
Email.send_later(:deliver_send_newsletter,user)
end
end
with or without the require items, it still gives me the same error ...
can anyone shed some light on this? or alternatively advise me on how to make a custom file within the script directory that will run this function (I already have a cron job working that will run and process all my delayed_jobs.
After Jonathans suggestion below I ran
env
as a cron job on its own and received the following output:
SHELL=/bin/sh
MAILTO=myemailaddress
USER=myusername
PATH=/usr/bin:/bin
PWD=/home/myusername
SHLVL=1
HOME=/home/myusername
LOGNAME= myusername
_=/usr/bin/env
does this mean it's not loading the ruby files properly?
....
also took Jonathans advice and produced the following cron.sh file
#!/bin/sh
date
echo "Executing Matenia Rake Task"
PATH=/usr/bin:/bin
cd /home/myusername/approotlocation/
rake sendnewsletter
still getting the missing gems notice ...
Cheers!
Easiest way to fix this (but kind of a shotgun approche) is from your shell type
env | grep PATH
Then take this output and add it your crontab for that user
so it would look something like this
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
# m h dom mon dow user command
42 6 * * * root job1
47 6 * * 7 root job2
52 6 1 * * root job3
Just make sure your gems's are inside of that path
When cron runs, it executes with a very minimal environment. Try running a cron job that just does env or which ruby, and you may see that your PATH is not the same as your interactive shell path. You'll need to specifically set the PATH in .bash_profile or another shell startup file.
I got around all of this by making a custom script/file and running that through cron. I dont know how, but it managed to work ...
Thanks for all the efforts.

How to set rails_env for a script or batch file

I put my batch file in lib folder
and use rails db configuration, active-record like this.
require "#{File.dirname(__FILE__)}/../config/environment.rb"
class Batch
def hello
Message.new do |t|
t.title = "hello"
t.save
end
end
end
batch = Batch.new
batch.hello
when excute batch
ruby lib/batch.rb
in development environment it's ok
but production environment still save development database...
how do i set rails_env batch.rb like this
ruby lib/batch.rb RAILS_ENV=production
To initialise the Rails environment, instead of putting
require "#{File.dirname(__FILE__)}/../config/environment.rb"
launch your batch file using script/runner and specify the environment with the -e option
e.g.
script/runner -e production lib/batch.rb
I think the above is The Rails Way of writing and executing a script that needs the Rails framework initialised in order to work. The alternative, as neutrino says, is to prefix the command with RAILS_ENV=value e.g.
$ RAILS_ENV=production lib/batch.rb
This is a standard shell feature to set an environment variable prior to executing a command.
Just FYI without script/runner :
RAILS_ENV=production ruby lib/batch.rb

Resources