Sasha
Sasha

Reputation: 6466

Command-line Ruby gem with configuration block

My gem named "Falcon" runs from the command line. Using ARGV and OptionParser, I read command-line input and run the main Ruby classes in my app, no problem.

It can take a configuration block in an initializer file as long as it is called from Rails Console. Following this basic pattern, I've made it so that users can create an initialization file like the following:

# config/initializers/falcon.rb

Falcon.configure do |c|
  c.allowed_setting = 'value'
end

And then, in the Rails Console, I can do this:

Falcon.configuration.allowed_setting # => 'value'

However, when I run from the command line, the gem classes work not with their set configuration options, but as if no configs have been set. I suppose it is because executing from the command line doesn't go through the Rails environment with its pre-loaded initialization files.

I've tried running bundle exec falcon [command], but that doesn't fix anything. Any ideas about how to get around this, so that the command line runs the gem with Rails configurations?

Upvotes: 0

Views: 159

Answers (2)

user229044
user229044

Reputation: 239551

There is no facility in Ruby to automatically load a configuration file. It's up to you to do so. You'need to ve been getting this behavior for free by running within a Rails environment where there are automatically-loaded configuration files, but you can't depend on this continuing to work outside of Rails.

You should add a -c or --config option to your program, that lets users specify the path to a configuration file, which you can load.

Upvotes: 1

TK-421
TK-421

Reputation: 10763

If your project is Rails-focused, you may want to consider building an engine instead (as it makes integration and testing far simpler).

Also, check out Application.initialize!.

Upvotes: 1

Related Questions