Skip to content

Instantly share code, notes, and snippets.

@markmcspadden
Created December 6, 2011 17:16
Show Gist options
  • Save markmcspadden/1439010 to your computer and use it in GitHub Desktop.
Save markmcspadden/1439010 to your computer and use it in GitHub Desktop.
My most shameful and most favorite Ruby of 2011
# Part of the Dallas Ruby "Best and Worst of 2011" showcase at the December 2011 meeting
# http://groups.google.com/group/dallasrb/browse_thread/thread/998dd95dd4677042
# Shame
@followings = current_profile.watch_events # NO LIMIT
# Fav
# Recursive Module Includes - yaml_dot_notation.rb
# This is an attempt to try to create a Hashie like dot notation
# for accessing nested elements within a yaml file.
# This seems a little "clever" but for certain uses,
# like tranversing a single branch of a very large yaml,
# it might prove more effective than other methods.
require 'yaml'
module Dot
def method_missing(method_name, *args, &block)
if result = self[method_name.to_s]
[result].flatten.each do |r|
class << r
include Dot
end
end
result
else
super
end
end
end
class Parser
attr_accessor :path, :doc
def initialize(path)
@path = path
end
def parse
doc = YAML::load(File.read(path))
class << doc
include Dot
end
doc
end
end
### TESTS
require 'test/unit'
class ParsingTest < Test::Unit::TestCase
def setup
@data = Parser.new('music.yaml').parse
end
def test_bracket_interface
assert @data["genres"].last["artists"].first["albums"].first["tracks"].last["name"] == "But Not For Me"
end
def test_dot_interface
assert @data.genres.last.artists.first.albums.first.tracks.last.name == "But Not For Me"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment