Shale is a Ruby object mapper and serializer for JSON, YAML and XML.
It allows you to parse JSON, YAML and XML data and convert it into Ruby data structures,
as well as serialize data structures into JSON, YAML or XML.
Working with data serialization formats directly can be painfull.
This is especially true for XML. Let’s consider this simple example of adding an
address to a person using Nokogiri
:
require ‘nokogiri’
doc = Nokogiri::XML(<<~XML) <person></person> XML address = Nokogiri::XML::Node.new('address', doc) street = Nokogiri::XML::Node.new('street', doc) street.content = 'Oxford Street' address.add_child(street) city = Nokogiri::XML::Node.new('city', doc) city.content = 'London' address.add_child(city) doc.root.add_child(address) puts doc.to_xml
That’s a lot of code for very simple use case.
Anything more complex and code complexity increases exponentially
leading to a maintanace problems and errors.
With Shale you can use Ruby objects to work with data
converting it to/from JSON, YAML or XML.
Let’s convert the same example to Shale:
require ‘shale’
class Address < Shale::Mapper
attribute :street, Shale::Type::String
attribute :city, Shale::Type::String
end
class Person < Shale::Mapper
attribute :address, Address
end
person = Person.from_xml(‘<person></person>’)
person.address = Address.new(street: ‘Oxford Street’, city: ‘London’)
puts person.to_xml
That’s much simpler and it stays simple when the code complexity increases.
Prerequisites
Shale doesn’t have external dependencies. It uses standard library’s
JSON
, YAML
and REXML
parsers by default.
If you need more performant solutions you can use custom libraries.
Out of the box, Shale provides adapters for Nokogiri
and Ox
– see how to use them.
Features
- Convert JSON, YAML and XML to Ruby data model
- Convert Ruby data model to JSON, YAML and XML
- Generate JSON and XML Schema from Ruby models
- Compile JSON Schema into Ruby models
- Out of the box support for JSON, YAML, Nokogiri, REXML and Ox parsers
- Support for custom adapters
Installation
Add this line to your application’s Gemfile:
And then execute:
Or install it yourself as:
Convert data to Ruby
Converting data to Ruby is as simple as defining model classes and calling
from_<format>
method on this class.
e.g. Person.from_json(json_doc)
Convert Ruby to data
To convert Ruby to data just define model class, initialize object and call
to_<format>
method on it.
e.g. P
~XML)
p>
Read More