Using YAML as a parameter hash in Ruby
Sometimes while coding Ruby applications the need develops to have some sort of metadata available as a configuration file. I have written some Ruby code that allows parameters that exist in a yaml file to be used as though they are in the class itself. In addition, I required code that allows the class to modify these parameters and then save them back to the file. Ruby's method_missing is a major player here. Anyway, I thought I would share this code.
To give an example of what exactly this does, assume that there exists a file called 'config.yml' that contains some key value pair such as :name => 'Bob':
--- :name: Bob
Using this class, we could do stuff like:
require 'boilerplate' class Test < Boilerplate def run puts "Name is: #{name}" super end end t = Test.new puts t.name #=> 'Bob' t.name = 'Joe' puts t.name #=> 'Joe' t.run #=> 'Name is: Joe'
Which would result in the yaml file now having the key value pair of :name => 'Joe'. If you didn't want to call 'run' you could call flush manually or add it as a call to some other method.
Here is the boilerplate.rb code in full:
class Boilerplate require 'yaml' require 'ftools' CACHE_LOCATION = File.join('.') CACHE_FILE = 'config.yml' CACHE_PATH = File.join(File.expand_path(CACHE_LOCATION), CACHE_FILE) def initialize ensure_cache_exists load_settings end def run # do stuff here flush end private def method_missing(symbol, *args, &block) string = symbol.to_s # need for '=' method if @options.key?(symbol) @options[symbol] elsif string.index('=') + 1 == string.length && @options.key?(string.gsub('=', '').intern) @options[string.gsub('=', '').intern] = *args else super(symbol, *args, &block) end end def load_settings @options = {} imports = YAML.load_file(CACHE_PATH) if imports imports.each_pair do |key, value| if not key.is_a? Symbol imports[key.to_sym] = value imports.delete(key) end end @options = imports.merge(@options) end end def ensure_cache_exists File.makedirs(CACHE_LOCATION) File.new(CACHE_PATH, 'a+') unless File.exists?(CACHE_PATH) end def flush File.open(CACHE_PATH, 'w') do |f| f.puts(YAML::dump(@options)) end end end
Recent comments
1 min 52 sec ago
1 min 55 sec ago
1 min 56 sec ago
1 min 56 sec ago
1 min 56 sec ago
1 min 56 sec ago
1 min 56 sec ago
1 min 57 sec ago
1 min 57 sec ago
1 min 58 sec ago