fscore
fscore

Reputation: 2619

Access a hash value from another ruby script

I have currently 2 APIs that require 2 different credentials. I want to commit my changes to Github but I dont want those credentials to be seen hence I decided to keep all my credentials in a hash in a separate ruby file and then want to access it in my script. At the same time, adding that file to .gitignore. But I am stuck in accessing that hash from my current script.

Here is my credentials.rb:

credentials = { 
    APIKEY: '12'
    PASSWORD: '34'
    sid: '45'
    token: '56'
}

Here is my main.rb:

class ApisController < ApplicationController

  def api
    url = "https://#{credentials[APIKEY]}:#{credentials[PASSWORD]}@test"
  end

end

I am not sure how do I call that hash in main.rb.

Upvotes: 0

Views: 735

Answers (1)

Bryan Dimas
Bryan Dimas

Reputation: 1452

There are three ways you can do this:

  1. There is the conventional & convenient way to do this in Rails. Add all your private credentials in an .environment file.
  2. Access a hash value from another ruby script that you gitignore.
  3. Or you can do it an even longer way, if you so insist.

First way: Use environment variables directly within the file where you need them. If you need them in yaml:

your_yaml_file.yml

 credentials_or_whatever:
       APIKEY: <%= ENV['API_KEY'] %>
       PASSWORD: <%= ENV['API_PASSWORD'] %>

Or if you need them in main.rb:

class ApisController < ApplicationController

  def api
    url = "https://#{credentials['APIKEY']}:#{credentials['PASSWORD']}@test"
  end

end

Second way: If for some reason you must use a hash that you gitignore instead of using just an environment file, then your credentials.rbcontains your credential that you later access where you need them. gitignored file:

credentials = { 
    "APIKEY": "12",
    "PASSWORD": "34"
    "sid": "45"
    "token": "56"
}

Then your main.rb:

class ApisController < ApplicationController

  def api
    url = "https://#{credentials["APIKEY"]}:#{credentials["PASSWORD"]}@test"
  end

end

Third way: Add your private credentials in environment variables and also then use them to create a hash that you gitignore:

Your credentials.rb file:

credentials = { 
    "APIKEY": ENV['APIKEY'],
    "PASSWORD": ENV['PASSWORD'],
    "sid": ['SID'],
    "token": ENV['TOKEN']
}

In first and second cases, your environment variables file might look like this:

.env(in your rails root folder):

APIKEY = 12
PASSWORD = 34
SID = 1234
TOKEN = 5678

I hope that helps to explain!

Upvotes: 1

Related Questions