This gems aims to provide a modern version of Struct. While Struct is a nice and easy way to create a light-weight value object, it has some drawbacks
- You need to remember the order of arguments
- The object is mutable by default
This gem aims to avoid these drawbacks, while providing the ease of use of Struct.
If you want to create a simple object, just declare it like you would declare a Struct:
Rectangle = StrictStruct.new(:x, :y) do
def area
x * y
end
end
This would conceptually create something like the following object:
class Rectange
attr_reader :x, :y
def initialize(x:, y:)
@x = x
@y = y
end
def to_h
to_hash
end
def to_hash
{
x: x,
y: y
}
end
def area
x * y
end
end
Since this is meant to create immutable objects, the values aren't actually assigned to instance variables but saved internally in a hash.
You can also choose to override behavior. You can just use super in the initialization block like you are used to with normal classes:
Rectangle = StrictStruct.new(:x, :y) do
def area
x * y
end
def to_hash
super.merge({area: area})
end
end
Add this line to your application's Gemfile:
gem 'strict_struct'
And then execute:
$ bundle
Or install it yourself as:
$ gem install strict_struct
- Fork it
- 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 new Pull Request