Super simple conversion of hashes into plain Ruby objects. Also works in RubyMotion.
Super simple conversion of hashes into plain Ruby objects. Also works in RubyMotion.
Very simple conversion of hashes to plain Ruby objects. This is great for consuming JSON API's which is what I use it for. Also works in RubyMotion.
Add this line to your application's Gemfile:
gem "dish"Then run:
$ bundleOr install it yourself:
$ gem install dishIf you want a to_dish helper method added to your Hash and Array objects, you can require dish/ext in your Gemfile:
gem "dish", require: "dish/ext"Dish fully supports RubyMotion, enabling you to easily consume JSON API's in your Ruby iOS apps.
For installation in RubyMotion, add this line to your project's Gemfile:
gem "dish", require: "dish/motion"Then run:
$ bundleAnd you're good to go.
NOTE: If you're using Dish with the BubbleWrap JSON module, please see below.
hash = {
title: "My Title",
authors: [
{ id: 1, name: "Mike Anderson" },
{ id: 2, name: "Well D." }
],
active: false
}
book = Dish(hash) # or hash.to_dish if you required "dish/ext"
book.title # => "My Title"
book.authors.length # => 2
book.authors[1].name # => "Well D."
book.title? # => true
book.active? # => false
book.other # => nil
book.other? # => falseValues can automatically be coerced, for example into a custom Dish object or a Time, for example if you have an updated_at in the source.
…This is inspired by Hashie's coercion methods.
Have fun!
You can use the Dish::Plate#to_h method for accessing the original hash. In addition Dish::Plate#to_json can be used for marshaling JSON if you are using RubyMotion (NSJSONSerialization is used) or have required the "json" Ruby stdlib.
NOTE: Previously Dish::Plate#to_h was called Dish::Plate#as_hash. The Dish::Plate#as_hash method is now deprecated.
When you use the BubbleWrap gem to parse JSON into a hash, you can't use the
Hash#to_dish methods directly because the BW::JSON module returns some sort of hash that hasn't got the methods from the real hash. I'm
fixing this, but in the meanwhile you can achieve the same result by doing this:
BW::HTTP.get("http://path.to/api/books/2") do |response|
json = BW::JSON.parse(response.body.to_s)
book = Dish(json) # This is the actual conversion
title_label.text = book.title
author_label.text = book.authors.map(&:name).join(", ")
endFeature additions are very welcome, but please submit an issue first, so we can discuss it in advance. Thanks.
git checkout -b my-new-feature)git commit -am 'Add feature')git push origin my-new-feature)No open issues yet, or sync has not completed.