Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the Figaro gem working only if I use erb syntax?

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?

like image 455
Daniel Romero Avatar asked Nov 28 '25 16:11

Daniel Romero


2 Answers

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.

like image 102
HackerKarma Avatar answered Dec 01 '25 07:12

HackerKarma


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.

like image 43
Sandy W Avatar answered Dec 01 '25 07:12

Sandy W



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!