A factory to create OpenStruct
objects from nested hashes and arrays.
The main difference with other gems such as recursive-open-struct is that this library is entirely decoupled: it doesn't inherit from OpenStruct
and doesn't rely on any core extensions.
Add this line to your application's Gemfile:
gem 'open_struct_factory'
And then execute:
$ bundle
Or install it yourself as:
$ gem install open_struct_factory
require 'ostruct'
require 'open_struct_factory'
book_data = {
title: "The World as Will and Representation",
author: {
name: "Arthur Schopenhauer",
birth_date: "1788-02-22",
birth_place: "Danzig",
},
publications: [
{edition: "1st edition", year: 1818},
{edition: "2nd expanded edition", year: 1844},
]
}
book = OpenStructFactory.create(book_data)
puts book.title
# => The World as Will and Representation
puts book.author.name
# => Arthur Schopenhauer
puts book.publications[1].year
# => 1844
A block can optionally be passed, it will be called for each key and give you the opportunity to sanitize the property name to be added to the OpenStruct
:
data = {
"SomePeople" => "LoveTheirCamelCase",
}
obj = OpenStructFactory.create(data) { |key| key.downcase }
puts obj.somepeople
# => LoveTheirCamelCase
- Fork it ( https://github.com/[my-github-username]/open_struct_factory/fork )
- 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 a new Pull Request