Elia Schito

rails runner… with a relative path

In Programming, Rails, Ruby, Ruby on Rails, Snippets on January 23, 2008 at 10:43 am

Well, you know what ./script/runner is?

If so, you’ll know you can’t use it to build script without using an absolute path in the shebang line in your custom scripts:

> ./script/runner -h
Usage: ./script/runner [options] ('Some.ruby(code)' or a filename)
You can also use runner as a shebang line for your scripts like this:
#!/usr/bin/env /path/to/your/app/script/runner

 So here’s the solution! (here the script is saved in the script dir)

#!/usr/bin/env ruby
unless $0 =~ /runner/
  exec("#{File.dirname(__FILE__)}/runner #{__FILE__}")
  # "exec" exits the current processing, so this comment won't reached (thanks to Arthaey Angosii)
# Your great script goes here!


#!/usr/bin/env ruby
$: << File.dirname(__FILE__)
ARGV[0] = __FILE__
load 'runner'
#your code here
  1. If you use exec() instead of backticks, STDOUT will continue to work. Otherwise, the backticks will swallow any writes to STDOUT by the rest of the script.

  2. You’re right, thanks for the suggestion! :)

  3. your alternative solution runs code twice ;)

  4. This one works, uses default environment. If you want to override the environment, set ENV(‘RAILS_ENV’)

    #!/usr/bin/env ruby
    require File.dirname(__FILE__) + ‘/../config/boot’
    require RAILS_ROOT + ‘/config/environment’

    puts “Running in environment #{RAILS_ENV}…”

    (your code goes here)

  5. I’ve had luck putting the path to the desired instance of runner in my $PATH and then making my shebang:

    #!/usr/bin/env runner

    I can then point to different instances of runner by manipulating my PATH variable before I invoke the script. I generally set it in environment setup scripts at login time.

    This method might not have been available when you wrote this blog entry, but it seems to work now with rails 2.3.4.

  6. Here’s a Rails 3 + Bundler version…

    #!/usr/bin/env ruby_noexec_wrapper

    unless defined? Rails
    ARGV.unshift “runner”, File.expand_path(__FILE__)
    require “rails/cli”

    # Insert script here!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: