stevec
stevec

Reputation: 52268

How to use an environment variable in a route in rails 5

I can make environment variables accessible to the app locally with a .env file

Problem is, I can't work out how to use the variable in a route

I have tried variations of

get 'v1/packages<%= ENV["key1"] %>' => 'flatfiles#raw'

Unfortunately this doesn't work (the browser says no route matches, but I can also tell from running rake routes which gives

GET  /v1/packages%3C%25=%20ENV[%22key1%22]%20%25%3E(.:format)

I also tried

get 'v1/packages#{ENV["key1"]}' => 'flatfiles#raw'

which makes the route

GET  /v1/packages%23%7BENV[%22key1%22]%7D

Neither method seems to insert the 'key1' variable into the route as I hope to do

For good measure, I also tried creating a Key model, and accessed it that way, but the route still interprets the variable literally

  @key1 = Key.find(1).private_key
  get 'v1/packages#{@key1}'  => 'flatfiles#raw'
GET /v1/packages_and_functions%23%7B@key1%7D

Upvotes: 2

Views: 1216

Answers (1)

zmo
zmo

Reputation: 24812

I believe your mistake is to try using format strings within a single quoted string:

get 'v1/packages#{ENV["key1"]}' => 'flatfiles#raw'

which means that the string is being taken as is. You shall be using double quotes instead, so that ruby can understand that you actually want a format within a string:

get "v1/packages#{ENV['key1']}" => 'flatfiles#raw'

If your editor has a proper support of syntax coloration, you'd notice that the former one would appear as a single color, whereas the second one will have the format part (#{}) highlighted.

Finally, the <%= ... %> syntax is only used within ERB templates, that Rails processes for you when you edit some .yml or html.erb files, or explicitely using ERB.new(...) within your code.

HTH

Upvotes: 2

Related Questions