5

Is there an easy way to test if the current directory is inside a rails project? Clearly Rails itself tests this in order to use the rails subcommands (generate, scaffold, etc.), so presumably there's a straight-forward way to test this.

I'm looking for something similar to how you would test if you're inside a Git repo.

Community
  • 1
  • 1
Adam Sharp
  • 3,618
  • 25
  • 29

3 Answers3

5

I know you already have a solution in ruby, but here's one written in bash, which should be a bit faster.

Assuming you're using Bundler:

grep 'rails' 'Gemfile' >/dev/null 2>&1
if [ $? -eq 0 ]; then
  echo "It's a Rails project!"
fi

This is what that snippet does:

  1. Grep the Gemfile in the current directory for 'rails'. Discard grep's output.
  2. If grep exits with exit code 0, you're in a Rails project

grep 'rails' 'Gemfile' will return a status code of 2 if a file named 'Gemfile' doesn't exist in the current directory. grep will return a status code of 1 if the found a 'Gemfile' but it doesn't contain 'rails'.

For Rails 2 without Bundler this should work:

if [ -f script/rails ]; then
  echo "It's a Rails 2 project!"
fi

All that does is test if the script/rails file exists.

I hope this helps someone who's hoping to do it bash instead of ruby.

cmoel
  • 148
  • 1
  • 8
1

There are no file or directory specific to Rails. so you can't really know if you are or not in a rails directory.

The better solution can be to know if you have rails or railities gem dependencies in your Gemfile.

bundle list | grep 'rail'
shingara
  • 46,608
  • 11
  • 99
  • 105
0

Upon further investigation, I was able to dig into the rails command itself and based a solution on part of the railties gem (<railties>/lib/rails/script_rails_loader.rb):

#!/usr/bin/env ruby

require 'pathname'

SCRIPT_RAILS = File.join('script', 'rails')

def self.in_rails_application?
  File.exists?(SCRIPT_RAILS)
end

def self.in_rails_application_subdirectory?(path = Pathname.new(Dir.pwd))
  File.exists?(File.join(path, SCRIPT_RAILS)) || !path.root? && in_rails_application_subdirectory?(path.parent)
end

if in_rails_application? || in_rails_application_subdirectory?
  exit(0)
else
  exit(1)
end
Adam Sharp
  • 3,618
  • 25
  • 29