Jim Flood
Jim Flood

Reputation: 8457

Best way to add binstub of thor-based utility CLI to Rails app

I have a thor-based CLI that goes with a Rails app, and among the teeming examples of using thor to implement a CLI, I don't find any examples of a simple binstub that would execute in the context of bundler.

I want to be able to call my_cli from the command line like this:

$ my_cli do something

I do NOT want to:

$ BUNDLE_GEMFILE=/path/to/Gemfile/of/Rails/app bundle exec my_cli

And I do NOT want to:

$ thor do something

The following binstub works. I have to require ../config/boot. Requiring 'thor/rails' in my_cli.rb is not enough.

I am asking, is there a better way to do this?

#!/usr/bin/env ruby
APP_PATH = File.expand_path('../../config/application', __FILE__)
require_relative '../config/boot'
require_relative '../lib/my_cli'
MyCli.start(ARGV)

Upvotes: 2

Views: 254

Answers (2)

Holden Omans
Holden Omans

Reputation: 26

A little cleaner:

#!/usr/bin/env ruby

ENV['BUNDLE_GEMFILE'] = File.absolute_path(File.join(__dir__, '../Gemfile'))
ENV['RAKEOPT'] = "--silent"
ENV['RAILS_ENV'] ||= 'development'

APP_PATH = File.absolute_path(File.join(__dir__, '../config/application.rb'))

require 'rubygems'
require 'bundler/setup'
require_relative '../config/environment'

require 'my_cli'

MyCli.start(ARGV)

Upvotes: 1

Jim Flood
Jim Flood

Reputation: 8457

This seems to work fine:

#!/usr/bin/env ruby

ENV['BUNDLE_GEMFILE'] = '/opt/myRailsApp/Gemfile'
ENV['RAKEOPT'] = "--silent"
ENV['RAILS_ENV'] ||= 'production'

APP_PATH = '/opt/myRailsApp/config/application'

require 'rubygems'
require 'bundler/setup'
require '/opt/myRailsApp/config/environment.rb'
require '/opt/myRailsApp/lib/my_cli'

MyCli.start(ARGV)

Upvotes: 0

Related Questions