Create struct-like classes that don't have setters, but have an awesome constructor.
Create struct-like classes that don't have setters, but have an awesome constructor.
Creates struct-like classes (that can build value objects) that do not have setters and also have better constructors than Ruby's built-in Struct.
This is highly useful for creating presenters, non-database-related models, or other quick and dirty classes in your application. Instead of using a Hash or OpenStruct, you can create a bit more clarity around your types by using ImmutableStruct, which is almost as convenient.
Add to your Gemfile:
gem 'immutable-struct'Then install:
bundle installIf not using bundler, just use RubyGems:
gem install immutable-struct…You can coerce values into struct types by using the from method. This is similar to Ruby's conversion functions, e.g. Integer("1").
dave = Person.from(p)
dave.equal?(p) # => true (object equality)
daveish = Person.from(dave.to_h)
daveish.equal?(dave) # => false
daveish == dave # => trueYou can treat the interior of the block as a normal class definition with the exception of setting constants. Use const_set to scope constants as-expected.
Point = ImmutableStruct.new(:x, :y) do
const_set(:ZERO, 0)
ONE_HUNDRED = 100
end
Point::ZERO # => 0
::ONE_HUNDRED # => 100
::ZERO # => NameError: uninitialized constant ZERONo open issues yet, or sync has not completed.