Bob K
Bob K

Reputation: 69

Trying to convert python code to ruby code

Here's the python code:

with open('config.json') as json_data_file:
       configuration = json.load(json_data_file)
       access_token=configuration["canvas"]["access_token"]
       baseUrl="https://"+configuration["canvas"]["host"]+"/api/v1/courses/"

header = {'Authorization' : 'Bearer ' + access_token}

I'm trying to write some code in ruby that does the exact same thing as the python code above. This is how I wrote it:

File.open("config.json") {|json_data_file|
  configuration = json.load(json_data_file)
  access_token=configuration["canvas"]["access_token"]
  baseUrl="https://"+configuration["canvas"]["host"]+"/api/v1/courses/"
}

header = {'Authorization': 'Bearer ' + access_token}

Is this the correct way to do it?

Upvotes: 0

Views: 727

Answers (1)

Noctilucente
Noctilucente

Reputation: 366

It's simpler than that. You use IO#read to return the file content as a string and then you use JSON.parse to convert JSON to a Ruby structure.

Say this is your config.json file:

{
  "canvas": {
    "access_token": "i like pie",
    "host": "ilikepie.com"
  }
}

And to access information from config.json in Ruby code:

# You need to require JSON
require 'json'

config_file = File.read('config.json')
config_hash = JSON.parse(config_file)

# Now you can access everything from `config_hash`
access_token = config_hash['canvas']['access_token'] # => 'i like pie'
host = config_hash['canvas']['host'] # => 'ilikepie.com'

Your final Ruby code should look something like this:

require 'json'

config = JSON.parse(File.read('config.json'))

access_token = config['canvas']['access_token']
host = config['canvas']['host']

# Use snake case in Ruby scripts. Also, use string interpolation, it's much clearer.
base_url = "https://#{host}/api/v1/courses/" # => 'https://ilikepie.com/api/v1/courses/'

Upvotes: 2

Related Questions