Gem Version Build Status Code Climate

DynamicClass

Many developers use OpenStruct as a convenient way of consuming APIs through a nifty data object. But the performance penalty is pretty awful.

DynamicClass offers a better solution, optimizing for the case where you need to create objects with the same set of properties every time, but you can't define the needed keys until runtime. DynamicClass works by defining instance methods on the class every time it encounters a new propery.

Let's see it in action:

Animal = DynamicClass.new do
  def speak
    "The #{type} makes a #{sound} sound!"
  end
end

dog = Animal.new(type: 'dog', sound: 'woof')
# => #<Animal:0x007fdb2b818ba8 @type="dog", @sound="woof">
dog.speak
# => The dog makes a woof sound!

cat = Animal.new
# => #<Animal:0x007fdb2b83b180>
cat.to_h
# => {:type=>nil, :sound=>nil}
# The class has been changed by the dog!

Because methods are defined on the class (unlike OpenStruct which defines methods on the object's singleton class), there is no need to define a method more than once. This means that, past the first time a property is added, the cost of setting a property drops.

The results are pretty astounding. Here are the results of the benchmark in bin/benchmark.rb (including a few other OpenStruct-like solutions for comparison), run on Ruby 2.2.4:

Initialization benchmark

Calculating -------------------------------------
          OpenStruct    14.668k i/100ms
PersistentOpenStruct    50.880k i/100ms
      OpenFastStruct    49.682k i/100ms
        DynamicClass    60.946k i/100ms
        RegularClass   107.521k i/100ms
-------------------------------------------------
          OpenStruct    165.010k (

DynamicClass is still behind plain old Ruby classes, but it's the best out of the pack when it comes to OpenStruct and friends.

Installation

Add this line to your application's Gemfile:

gem 'dynamic_class'

And then execute:

$ bundle

Or install it yourself as:

$ gem install dynamic_class

Development

After checking out the repo, run bin/setup to install dependencies. Then, run rake spec to run the tests. You can run the benchmark using rake benchmark. You can also run bin/console for an interactive prompt that will allow you to experiment.

To install this gem onto your local machine, run bundle exec rake install.

Contributing

Bug reports and pull requests are welcome. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the Contributor Covenant code of conduct.

For functionality changes or bug fixes, please include tests. For performance enhancements, please run the benchmarks and include results in your pull request.

License

The gem is available as open source under the terms of the MIT License.