Skip to content

Instantly share code, notes, and snippets.

@wyattdanger
Created March 20, 2012 02:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wyattdanger/2130136 to your computer and use it in GitHub Desktop.
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
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
@postpostmodern
Copy link

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:

class YAMLReader < OpenStruct
  def initialize yaml_file_path
    super(YAML.load_file(yaml_file_path))
  end
end

@postpostmodern
Copy link

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

@wyattdanger
Copy link
Author

@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