One nice thing about Java is its use of properties files, which are text files with a .properties extension that contain key-value pairs of data. This way, changeable data can be stored in a file separate from the code. There is a way to do this in Ruby too, with YAML files and the Ruby YAML module.
First, create a YAML file. This is simply a text file with a .YAML extension, and with key-value pairs of data seperated by a colon. For example, let’s say you wanted to store a user name and password to run your tests with (for illustration purposes – normally it’s not a good idea to store a password in a text file). You’d set up your properties.yaml file thus:
username : jim
password : mypassword
Save the file. Now, you can access those properties through Ruby. Since I love using IRB to test functionality interactively, I’ll recommend you now fire up IRB. For this example, run IRB from the directory you created the YAML file.
Once IRB is up, require the YAML module:
require ‘yaml’
Now, load the properties file and assign it to a variable:
properties = YAML.load_file( './properties.yaml' )
Once this is done, you can use the properties from your YAML file. Let’s say you had a login() method that takes two parameters, the username and password. You could at this point run your method thus:
login(properties[“username”], properties[“password”])
This will run your login() method with the username and password you defined in your properties.yaml file.
Design principles:
- For properties that will not change, I’d suggest you can define those in helper modules.
- For properties that will change in different environments, put them in a YAML file. This makes it much easier to customize a deployment.
No comments:
Post a Comment