Ruby Xocolatl

Ruby, Cocoa, Mac OS X and things of my not so exciting life.

FreeBSD Startup Script With Ruby

Since some days ago I’ve been using FreeBSD in a Rails deployment server configuring it to use Capistrano, nginx and mongrel but then I wanted my mongrel instances to be run at startup and what I found was this message:
Put your .sh script at /usr/local/etc/rc.d
And since I like ruby, I began to code my script with it and the problems came:
env: ruby: No such file or directory
custom_require.rb:27: command not found: mongrel_rails
First, here is my final code that was inspired by Tim Morgan’s:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#!/usr/local/bin/ruby

puts ENV["PATH"] += ":/usr/local/bin"
app_dir = '/usr/local/www'

apps = [
  scielo_index = { :name => "ScieloIndex",
                   :path => 'index.scielo.unam.mx/current',
                   :config => "config/mongrel_cluster.yml",
                   :cluster => true },

  redmine = { :name => "Redmine",
              :path => 'dev.scielo.unam.mx/Redmine',
              :config => "config/mongrel_8000.yml",
              :pid => "log/mongrel.pid" }
  ]

if ['stop', 'restart'].include? ARGV.first
  apps.each do |app|
    path = File.join app_dir, app[:path]
    puts "Stopping #{app[:name]}..."
    if app[:cluster]
      `mongrel_rails cluster::stop -C #{path}/#{app[:config]}`
    else
      `mongrel_rails stop -c #{path} -P #{app[:pid]}`
    end
  end
end

if ['start', 'restart'].include? ARGV.first
  apps.each do |app|
    path = File.join app_dir, app[:path]
    puts "Starting #{app[:name]}..."
    if app[:cluster]
      `mongrel_rails cluster::start -C #{path}/#{app[:config]}`
    else
      `mongrel_rails start -C #{path}/#{app[:config]}`
    end
  end
end

unless ['start', 'stop', 'restart'].include? ARGV.first
    puts "Usage: mongrel {start|stop|restart}"
    exit
end
The key part is the ENV[“PATH”] setup, that line is needed as FreeBSD’s PATH at startup is “/sbin:/bin:/usr/sbin:/usr/bin” and this also leads us to change the interpreter path from something like “#!/usr/bin/env ruby” to “#!/usr/local/bin/ruby”, i.e. its full path. That’s all, now our ruby script really runs at startup time without complaining.