Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test if the current directory is inside a Rails project (bash)

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.

like image 494
Adam Sharp Avatar asked Apr 05 '12 06:04

Adam Sharp


People also ask

How do I get the current directory in Ruby?

pwd : To check the current working directory, pwd(present working directory) method is used. 5. chdir : To change the current working directory, chdir method is used.

What is __ DIR __ in Ruby?

__dir__ is a alias to a function As the ruby documentation says __dir__ is equal to File.dirname(File.realpath(__FILE__))

How to launch rails?

Go to your browser and open http://localhost:3000, you will see a basic Rails app running. You can also use the alias "s" to start the server: bin/rails s . The server can be run on a different port using the -p option. The default development environment can be changed using -e .


2 Answers

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.

like image 88
cmoel Avatar answered Sep 27 '22 16:09

cmoel


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'
like image 29
shingara Avatar answered Sep 27 '22 17:09

shingara