OpenFastStruct

Code Climate Build Status

OpenStruct allows the creation of data objects with arbitrary attributes.

OpenFastStruct is a data structure, similar* to an OpenStruct, that allows the definition of arbitrary attributes with their accompanying values. It benchmarks ~3x slower than a Hash, but it's ~4x faster than OpenStruct.

*An OpenFastStruct is not exactly like an OpenStruct, these are the main differences between them:

  • OpenFastStruct doesn't allow hash access like person[:name].
  • OpenFastStruct doesn't provide marshalling.
  • OpenFastStruct allows infinite chaining of attributes example.

Installation

Install the gem:

$ gem install ofstruct

Use the gem in a project managed with Bundler adding it into the Gemfile:

gem "ofstruct"

Examples

Basic usage

require "ofstruct"

person = OpenFastStruct.new
person.name = "John Smith"
person.age  = 70

puts person.name     # -> "John Smith"
puts person.age      # -> 70
puts person.address  # -> #<OpenFastStruct>

Initialize and update from a Hash

An OpenFastStruct employs a Hash internally to store the methods and values and can even be initialized or updated with one:

require "ofstruct"

person = OpenFastStruct.new(:name => "John Smith")
puts person.name  # -> "John Smith"

person.update(:name => "David Smith", :age => 70)
puts person.name  # -> "David Smith"
puts person.age   # -> 70

Remove attributes

Removing the presence of a method requires the execution the #delete_field method as setting the property value to a new empty OpenFastStruct.

require "ofstruct"

person = OpenFastStruct.new
person.name = "John Smith"
person.delete_field(:name)
puts person.name  # -> #<OpenFastStruct>

Black hole object

An OpenFastStruct instance is a black hole object that supports infinite chaining of attributes.

require "ofstruct"

person = OpenFastStruct.new
person.address.number = 4
puts person.address.number  # -> 4

Benchmarks

Probably you heard that you should never, ever use OpenStruct because the performance penalty is prohibitive. You can use OpenFastStruct instead!

Comparation between Hash, OpenFastStruct and OpenStruct:

$ ruby benchmark/hash_ofstruct_ostruct.rb
Calculating -------------------------------------
                Hash    25.518k i/100ms
      OpenFastStruct    10.527k i/100ms
          OpenStruct     3.236k i/100ms
-------------------------------------------------
                Hash    487.517k (

Comparation between RSpec Stubs, OpenFastStruct and OpenStruct:

$ ruby benchmark/double_ofstruct_ostruct.rb
Calculating -------------------------------------
         RSpec Stubs   103.000  i/100ms
      OpenFastStruct   108.000  i/100ms
          OpenStruct    45.000  i/100ms
-------------------------------------------------
         RSpec Stubs    297.809  (