Skip to content

Instantly share code, notes, and snippets.

@dotmh
Created August 7, 2011 12:40
Show Gist options
  • Save dotmh/1130341 to your computer and use it in GitHub Desktop.
Save dotmh/1130341 to your computer and use it in GitHub Desktop.
This is a work in progress of a wrapper for YML files , and an example class using the module
# This builds on the YAML Interface so I need to require it here.
require 'yaml';
# This is my YAML helper it is meant to wrap a YML file and allow you to access
# it has if it was a class, giving you access to the data contained in the hash
# in a OOP way. Still needs a little work especially with the casscade.
module DMH_Yaml_Helper
# This holds the configuration hash file
@hash
# Holds the filename for the config file this is if you need to save later
@filename
# Opens a configuration YAML file and holds in in @hash
# Raises an exception if file doesn't exist
def open filename
@filename = filename
raise "File "+filename+" Doesn't exist" unless File.exist?(filename)
@hash = YAML::load(File.open(filename))
p @hash
end
# An Alias of save but excepts the filename as a param
def new_config filename
@filename = filename
save
end
# Saves the config data back into the file
def save
yaml = @hash.to_yaml();
f = File.new(@filename , 'w+')
yaml.each do |line|
f.puts line
end
f.close
end
# This handles the call to data so that you can act on the hash
# To get data then do class.option_you_want
# You can go down multiple levels by passing it after the first option
# i.e class.option_you_want next_level_down
#
# To set the data you can use the = syntax , i.e. class.option_to_set = value
# Current setting can not be down on multiple leves only the top branch can
# be set.
def method_missing name , *args
if ( node = /^=(\w*?)$/.match name )
set node[1].to_sym , args
elsif ( node = /^(\w*?)$/.match name)
data = get node[1].to_sym
args.each { |arg| data = get arg, data } if args.respond_to?('each')
else
data = false
end
data
end
private
# The is the private method used to get values from the hash , used by
# missing method , it takes the key to get and optionally the hash to get it
# from , hence why you can go down levels using it.
def get key , on = @hash
data = on.fetch key , false
end
# This is the private key to set hash values
def set key , value
@hash.store key , value
end
end
# This module implents my Yaml_Reader module wrapping it in a class called
# DMH_Yaml_Helper to allow you to quickly use YAML files for configuration
# settings
module DMH_Yaml_Config
# This class implements the Yaml_Reader module and wraps its methods in a class
# helper
class Handler
include DMH_Yaml_Helper
# This acts as a construct that opens a configuration file and stores it in
# The hash allowing you to access it with the functions above
def initialize filename
open filename
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment