Volte
Volte

Reputation: 1905

Find root of project from included gem

Here's the scenario. I'm writing GemB, and I plan to use it in ProjectA, but I want to write GemB in a non-specific fashion (as I should). I want GemB to look for a "config" file under a "conventional" project_a/config/gem_b.yml

If that file doesn't exist, GemB can default to it's own gemb/config/default.yml

ProjectA (probably is a variant of a gem/rails-engine/rails-app etc) GemB (definitely a gem)

Is there a dynamic way for GemB to get the root of ProjectA (the project it's being used in)? If I could predict the name, I could call ProjectA.root (likely), so you might suggest calling Rails.root but I can't guarantee that it will be used in a Rails project, (and in this case unlikely anyway, based on the target functionality of GemB).

Trusting that's a sufficient explanation, let me know if I need to clarify!

Upvotes: 0

Views: 51

Answers (1)

moveson
moveson

Reputation: 5213

Most modern gems don't look for a particular config file. Instead, they expect a config file of any name to be executed, which will set configurations via a .config variable on the gem's class name. For example, I might have this config file:

# config/initializers/ams.rb

ActiveModelSerializers.config.adapter = :json_api
ActiveModelSerializers.config.key_transform = :camel_lower

Now it doesn't matter where the file is located or what it's called. So long as the code is executed, ActiveModelSerializers can look at its own ActiveModelSerializers.config variable and it is good to go.

If you wanted an extensive configuration (by means of a .yml file, for example) you might create a .config.path setting and instruct users of your gem to set the path themselves and then create a file in the spot they choose:

# config/initializers/gem_b.rb

GemB.config.path = '/config/gem_b.yml'

Upvotes: 2

Related Questions