سؤال

I'm using the Figaro gem but it only works when I access the env variables inside config/database.yml like this:

<%= ENV["MYSQL_USERNAME"] %>

but not when I try it the way the docs specify:

ENV["MYSQL_USERNAME"]

or

Figaro.env.mysql_username

Does anyone know why is that?

هل كانت مفيدة؟

المحلول 2

Their documentation is wrong. If you want to interpolate a non-static value into a YAML file, you have to use the ERB tags. YAML files are generally just static files. Rails processes database.yml through an ERB parser, which is why you can interpolate values using ERB syntax.

To put it another way: if you don't use the ERB tags, Rails doesn't know if it should evaluate what you've typed, or if it should treat it as a static value.

نصائح أخرى

Figaro Gem's official documentation clearly says (see "Give me an example" section) the following:

NOTE: Figaro uses Rails' standard hooks to initialize. Unfortunately, this hook apparently occurs after database.yml is read. Because of this issue, environment variables created in application.yml don't work inside database.yml.

Upon investigating further I found out few issues were raised regarding this. Steve Richert (creator of Figaro Gem with "laserlemon" Github id) says this on the issue #70

This is a known issue. We use Rails' standard hooks to initialize Figaro before Rails initializes. Unfortunately, this hook apparently occurs after database.yml is read. Trying to circumvent the standard hooks and tie into Rails' initialization elsewhere introduces a host of new problems and makes it very difficult to account for every situation in which the Rails environment is loaded. I'm afraid this falls into the "won't fix" bucket until Rails provides a better (and supported) hook that Figaro can tie into...

UPDATE:

As per the pull request #100 the database.yml config is working with fine latest version of both Rails (like 4.0 and 4.1) and Figaro.

Finally, I highly recommend reading Rails Environment Variables guide by Taylor Mock and Daniel Kehoe. This is a MUST read for all RoR developers.

If you are accessing ENV["MYSQL_USERNAME"] within an ERB file then obviously you need to use <%= %> to evaluate and print the evaluated ruby code.

If you simple use ENV["MYSQL_USERNAME"] without <%= %> then it will not be interpreted by ERB Template Engine. It would be treated as plain text.

EDIT

Your question did not specify where you are accessing ENV["MYSQL_USERNAME"] initially(it was added later after posting comment to my answer) thats why I assumed that it was in ERB file. In any .rb file you don't need to specify <%= %> while accessing ENV. But you do need to specify them to access within .yml or .erb files.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top