Alternatives to OpenStruct

OpenStruct is bad. I prove it below, but it's also been done before (see: this, this and this). Here are two quick alternatives.

First, there's ClassyStruct, used like so:

require 'classy_struct'
Widget = ClassyStruct.new

w1 = Widget.new

w1.foo = :bar
w1.foo  # => :bar

w1 = Widget.new(:foo => :bar, :baz => {:xyzzy => :thud})
w1.foo        # => :bar
w1.baz.xyzzy  # => :thud

Second, and less optimal, you can monkey patch Hash, like so:

class Hash
  def method_missing(meth, *args, &block)
    if meth =~ /^(.+)=$/
      self.store($1.to_sym, args[0])
    else
      if self.has_key?(meth)
        self[meth]
      else
        super
      end
    end
  end
end

And use it like so:

h = {}
h.foo = :bar
h.foo # => :bar

I'll prove it.

Benchmarks:

user     system      total        real
open  0.060000   0.000000   0.060000 (  0.065261)
clas  0.020000   0.000000   0.020000 (  0.018233)
hash  0.440000   0.000000   0.440000 (  0.439549)

See the benchmarking code used to generate this here: https://gist.github.com/3997825.

Published on in Ruby