First, let's go to app.rb
and look at our list of required Gems:
require 'sinatra'
We're going to need two additional Gems, which are as follows:
json
: We'll use it to convert the JSON text in VCAP_SERVICES
into a data structuremysql2
: We'll use it to access the MySQL databaseThe expanded Gem requirements are as follows:
require 'sinatra' require 'json' require 'mysql2'
At the beginning of the application, we add new code that extracts MySQL credentials from the VCAP_SERVICES
. This environment variable contains a JSON string that parses into a data structure similar to this example:
{ "mysql-5.1"=>[ { "name"=>"insideaf-mysql", "label"=>"mysql-5.1", "plan"=>"free", "tags"=>["mysql", "mysql-5.1", "relational", "mysql-5.1", "mysql"], "credentials"=>{ "name"=>"d72374bco5g9u4s4f9e06e8e6014bdfdf", "hostname"=>"10.0.36.89", "host"=>"10.0.36.89", "port"=>3306, "user"=>"uroCGNAJpmoK6", "username"=>"uroCGNAJpmoK6", "password"=>"p4gGbogusJ7Il" } } ] }
The code must perform the following steps:
mysql-5.1
, since this is the array of MySQL services.name
key with a value that matches the service we want.credentials
whose value is a hash containing the credentials we need. Extract it.These steps are easier to express in Ruby than in English. If the name of the service is insideaf-mysql
then this is the code that extracts the credentials:
creds = (JSON.parse(ENV['VCAP_SERVICES'])['mysql-5.1'].each do |s| break(s) if s['name'] == 'insideaf-mysql' end)['credentials']
Next we use the credentials to connect to the database:
client = Mysql2::Client.new(:host => creds['host'], :username => creds['user'], :password => creds['password'], :database => creds['name'], :host => creds['host'], :port => creds['port'])
Finally, we need to change the code that responds to the page request. The old version looks like the following code:
get '/' do @env = ENV erb :index end
In the new version, the instance variable is set to the results variable for a database query:
get '/' do @rows = client.query('select * from Tasks', :cast_booleans => true) erb :index end
The following code is the entire source file in one place:
require 'sinatra' require 'json' require 'mysql2' creds = (JSON.parse(ENV['VCAP_SERVICES'])['mysql-5.1'].each do |s| break(s) if s['name'] == 'insideaf-mysql' end)['credentials'] client = Mysql2::Client.new(:host => creds['host'], :username => creds['user'], :password => creds['password'], :database => creds['name'], :host => creds['host'], :port => creds['port']) get '/' do @rows = client.query('select * from Tasks', :cast_booleans => true) erb :index end
3.137.163.62