ChocMool
Wraps a hash, allowing easy access to deeply nested values.
Installation
gem 'choc_mool'
Usage
hash = {one: {two: {three: :four}}}
data = ChocMool.new(hash)
data.fetch(:one, :two, :three)
# => :four
using a regex
hash = {one: 'two, three'}
data = ChocMool.new(hash)
data.using(/^(.*),/).fetch(:one)
# => 'two'
using dot notation
hash = {one: {two: {three: :four}}}
data = ChocMool.new(hash)
data.fetch('one.two.three')
# => :four
data.fetch(:one, 'two.three')
# => :four
accessing attributes
A common use for ChocMool is to easily access deeply nested data returned from APIs. The API data is converted to hash from XML or JSON then wrapped by ChocMool.
XML cannot be represented directly by a hash, thus libraries that convert the XML -> hash can expose this data.
ChocMool supports accessing these values when they are accessed via
#attributes
on the corresponding key (as provided by Nori).
xml = "<one two='three'>four</one>"
hash = Nori.new.parse(xml)
data = ChocMool.new(hash)
data.fetch(:one, '@two')
# => 'three'
data.fetch(:one)
# => 'four'
accessing arrays
hash = {one: [:two, :three]}
data = ChocMool.new(hash)
data.fetch(:one, 1)
# => :three
data.fetch_each(:one) { |value| puts value }
# => :two
# => :three
data.fetch_each_with_index(:one) { |value, index| puts "#{index}: #{value}" }
# => 0: :two
# => 1: :three
Contributing
- Fork it
- Create your feature branch (
git checkout -b my-new-feature
) - Commit your changes (
git commit -am 'Add some feature'
) - Push to the branch (
git push origin my-new-feature
) - Create new Pull Request
Links
- repo: http://github.com/attack/choc_mool
- travis ci: https://travis-ci.org/attack/choc_mool
- code climate: https://codeclimate.com/github/attack/choc_mool
Copyright
Copyright (c) 2013-2014 Mark Gangl. See LICENSE for details.