Last Updated: February 25, 2016
·
1.529K
· lcguida

Configuring DataMapper with a YAML file

Did you know DataMapper cab be set up with a hash specifying the options? Although it's not very clear in it's documentation, it's possible!

For example, setting up a MySQL adapater with DataMapper, following the documentation:

DataMapper.setup( :default, 
        "mysql://<user>:<password>@<hostname>:<port>/<database>")

How can I achieve the result with a Hash ?

options = { adapter: mysql, hostname: "<hostname>", port: "<port>", 
            user: "<user>", password: "<password>" }
DataMapper.setup(:default, options)

"Oh, I saw what you did there!". DataMapper reconizes the adapter passed by the Hash creates the correct database connection.

Do you want to make even better? Put these options in a YAML file:

#datbase.yml

adapter: mysql
hostname: "<hostname>"
port: "<port>"
user: "<user>"
password: "<password>"

And then load into DataMapper:

options = YAML.load_file('database.yml')
DataMapper.setup(:default, options)

You can also put multiple configurations to a YAML file and load multiple DataMapper's:

#datbase.yml

default:
  adapter: mysql
  hostname: "<hostname>"
  port: "<port>"
  user: "<user>"
  password: "<password>"

another_database:
  adapter: mysql
  hostname: "<another_hostname>"
  port: "<port>"
  user: "<another_user>"
  password: "<another_password>"
options = YAML.load_file('database.yml')
DataMapper.setup(:default, options['default'])
DataMapper.setup(:another, options['another'])

2 Responses
Add your response

Hey, so YAML 1.2 is a superset of JSON, so, dump it with YAML.to_json({}) and you'll get a file readable by both yaml and json. perhaps at the cost of some human readability, but still, good to know.

over 1 year ago ·

Yeah.. it is good to know.. ;)

over 1 year ago ·