jerzy
jerzy

Reputation: 2654

What's inside my rails ./bin directory?

Ruby on Rails 4 introduced* the ./bin directory. Inside of ./bin are a few executables: bundle, rails, rake, setup, spring.

My questions are:

  1. What do these executables do? Why do they exist?
  2. When are they invoked?
  3. Can I edit them? Why would I edit them?

I've read the source of these files, and I've tried to Google their purpose, but I can't wrap my head around it. I'm looking for an in-depth explanation.

*I believe many of these files existed before Rails 4, just in different location.

Upvotes: 26

Views: 10898

Answers (2)

jerzy
jerzy

Reputation: 2654

Introduced in Rails 4, the ./bin directory contains your app's "binstubs." Binstubs are wrappers around gem executables, like rails or bundle, which ensures a gem executable is run inside the correct environment for your Rails app.

Binstubs can be used in lieu of bundle exec to run a gem's executable inside your app's environment. For example, instead of typing bundle exec rails scaffold products you can type bin/rails scaffold products. Using binstubs is more flexible than bundle exec, because you don't have to cd to the app's root directory and type bundle exec before everything.

By default, bundle, rails, rake, setup, spring binstubs are created automatically for new rails projects. To make a binstub for a gem executable, just type bundle binstubs name_of_gem_executable. You'll find the new binstub in your ./bin directory.

Some suggest putting ./bin in your shell's search $PATH, so that you don't have to type bin/rails and you can just type rails. This is risky because it depends on ./bin coming before the gem executable's path in $PATH; if you happen to forget this ordering and adjust $PATH such that the gem's executable is found before the binstub wrapper, you could easily invoke the gem's executable -- sans the environmental pretext -- without realizing it.

Upvotes: 39

muichkine
muichkine

Reputation: 2940

A bin (short for binary) is nothing more than an application. As you have noticed, these files are ruby files, but they do not have the .rb extension and can be run from your shell just as any shell command, without the need to start any ruby interpreter yourself.

So what do theses programs do? I'm pretty sure you know already what rails rake bundle do.

About spring, it's a gem that keeps your app running in the background (hence its need to be run independently from the app). More infos on their github.

I see no reason to edit these files, but that being said, they're ruby files so you can do whatever you want with them. One example of why you may want editing can be found here.

I personally do put some stuffs in the bin folder. Scripts to connect to remote servers, or ruby scripts I need but that I don't want to run as rake tasks since they're more general than my application.

Upvotes: 4

Related Questions