gates
gates

Reputation: 4583

How to use environment variables once declared

I am trying to an use an environment variable as an API key, but once when using it. The ruby interpreter gives me constant un initialised error. Can anyone draw some light on this. I seem to find no resource explaining how to use them after declaration. Here is my code

require 'httparty'

class Recipe
  include HTTParty

  ENV['FOOD2FORK_KEY'] = 'key'  
  base_uri 'http://food2fork.com/api'
  default_params key: FOOD2FORK_KEY
  format :json

  def self.for term
    get("", query: { q: term})
  end

end

Upvotes: 1

Views: 755

Answers (2)

Schwern
Schwern

Reputation: 164689

You access environment variables inside Ruby with the ENV class.

default_params key: ENV['FOOD2FORK_KEY']

You generally shouldn't be setting environment variables inside a Ruby application, except maybe for testing. They should be set by the system calling your application.

Upvotes: 2

mic4ael
mic4ael

Reputation: 8290

You should use it like this ENV['FOOD2FORK_KEY']. This will return the value of the given key. See details here http://ruby-doc.org/core-2.2.0/ENV.html

Upvotes: 3

Related Questions