bundle binstubs

In Ruby, we use Bundler to manage the gem in our projects. We also use bundle exec prefix to run the command in our projects for ensuring that it’s running in current bundler. Eg.

1
bundle exec rake db:migrate

But, it seems a little inconvenient so that we can use binstubs to omit it. Assume that we want to generate binstubs of rake:

1
bundle binstubs rake

This will generate rake script in the bin folder, and now we can run

1
./bin/rake

equal to

1
bundle exec rake

If you want to generate all binstubs of this project, you can run

1
bundle install --binstubs

But I don’t recommend this because it will generate a config .bundler in the same time. It will re-generate all binstubs when you run bundle install. It will overwrite all the binstubs so that you can not use some gem like spring.

Environment Variable

But we still need to type ./bin/. To solve this, we can add ./bin to environment variable PATH. In Mac we can modify .bash_profile

1
vi ~/.bash_profile

Add

1
export PATH="./bin:$PATH"

We have to prepend at first for first priority. And now, we can type rake directly.

direnv

If we use rvm, the above method will not work because rvm will overwrite the PATH. In this case, we can use direnv to solve it. We use brew to install:

1
brew install direnv

And add following config to .bash_profile

1
eval "$(direnv hook bash)"

And create .envrc in the project folder, add this:

1
PATH_add bin

After that, it will add bin to environment variable PATH if we enter the project folder. You maybe see the error message at first time.

1
direnv: error .envrc is blocked. Run `direnv allow` to approve its content.

According to the hint, enter:

1
direnv allow

Allow it apply the setting.