Shale
Shale 是一个用于 JSON、YAML 和 XML 的 Ruby 对象映射器和序列化器。
它允许您解析 JSON、YAML 和 XML 数据并将其转换为 Ruby 数据结构,以及将数据结构序列化为 JSON、YAML 或 XML
Introduction
直接使用数据序列化格式可能会很痛苦。对于 XML 尤其如此。让我们考虑这个使用 Nokogiri 向某人添加地址的简单示例:
require 'nokogiri'
doc = Nokogiri::XML(<<~XML)
<person></person>
XMLaddress = 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
对于非常简单的用例来说,这是很多代码。任何更复杂的代码和代码复杂性都会以指数方式增加,从而导致维护问题和错误。
借助 Shale,您可以使用 Ruby 对象处理将其转换为 JSON、YAML 或 XML 的数据。
让我们将相同的示例转换为 Shale:
require 'shale'
class Address < Shale::Mapper
attribute :street, Shale::Type::String
attribute :city, Shale::Type::String
endclass Person < Shale::Mapper
attribute :address, Address
endperson = Person.from_xml('<person></person>')
person.address = Address.new(street: 'Oxford Street', city: 'London')puts person.to_xml
这要简单得多,并且在代码复杂性增加时保持简单。
Prerequisites
.......................
文章来自:https://www.shalerb.org/