Skip to content

maiha/hash-path

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

8 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

hash-path
=========

  path accessor to hierarchical hash


Class
=====

  * HashPath
      .path    : define path accessor
      .paths   : defined paths


Example
=======

  # JSON.parse(...) returns like this
  hash = {
    "Name" => "foo",
    "Body" => "content",
    "Additional" => {
      "Code" => 1234,
      "StartDateTime"=>"2010/01/10 19:30"
    }
  }

  class Item < HashPath
    path :name, "Name"
    path :body, "Body"
    path :code, "Additional/Code"
    path :time, "Additional/StartDateTime"

    def time
      Time.parse(super)  # parse is defined in active_support, night-time,... gem
    end    
  end 

  item = Item.new(hash)
  item.name  # => "foo"
  item.code  # => 1234
  item.time  # => Sun Jan 10 19:30:00 +0900 2010


Advanced
========

  # Extends HashPath to accept jsonpath syntax for path value.
  # Install gem first, and then require 'hash-path/json'.
  #
  #   gem install jsonpath

  require 'hash-path/json'

  hash = {
    "name"=>"Buono",
    "members"=>
      [{"name"=>"momo", "age"=>17},
       {"name"=>"miya", "age"=>17},
       {"name"=>"airi", "age"=>15}]
  }

  class Group < HashPath
    path :leader              , "$..members[0]"
    path :middle_school_member, "$..members[?(@['age'] <= 15)]"
  end

  group = Group.new(hash)
  group.leader                # => [{"name"=>"momo", "age"=>17}]
  group.middle_school_member  # => [{"name"=>"airi", "age"=>15}]


Todo
====

  * convert value to some type automatically


Author
======

  [email protected]

About

path accessor to hierarchical hash

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages