Created
March 20, 2012 02:12
-
-
Save wyattdanger/2130136 to your computer and use it in GitHub Desktop.
class that accepts a yaml file and dynamically creates getters/setters for each yaml key
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class YAMLReader | |
def initialize yaml_file_path | |
YAML.load_file(yaml_file_path).each do |key, value| | |
self.class.instance_eval do | |
attr_accessor :"#{key}" | |
end | |
self.send "#{key}=", value | |
end | |
end | |
end |
Here's a more complete version. The only problem is, dumping and/or saving will convert yaml keys to symbols, but it's way past bedtime. :)
require 'ostruct'
require 'yaml'
class YAMLReader < OpenStruct
def initialize yaml_file_path
@file_path = yaml_file_path
super(YAML.load_file(@file_path))
end
def dump
marshal_dump.to_yaml
end
def save
save_as @file_path
end
def save_as(new_file_path)
File.open( new_file_path, 'w' ) do |out|
YAML.dump( marshal_dump, out )
end
end
end
@postpostmodern that certainly helped clean things up a bit: wyattdanger/YAML-Reader@a6e1ab5
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Have you thought about using OpenStruct? It'll basically do the same thing you have done here. You could write your reader class like this: