Hash-Initialized Struct
Halfway between Struct and OpenStruct. (Or: Struct, except it takes a Hash on object initialization.)
Ignore if you already use Virtus or Hashie::Dash.
Usage
class Point < HashInitializedStruct.new(:x, :y); end
# Or: Point = HashInitializedStruct.new(:x, :y)
point = Point.new(x: 1, y: 2)
point.x # => 1
unknowns = Point.new(x: 1, y: 2, z: 3)
# => raises ArgumentError, "Unrecognised keys: :z"
missing = Point.new(x: 1)
# => raises ArgumentError, "Missing keys: :y"
Fancy Usage
class Point < HashInitializedStruct.new(:x, :y)
def initialize(attrs)
super
[x, y].each do |attr|
raise ArgumentError, "#{attr} must be a number" unless attr.kind_of?(Numeric)
end
end
end
good = Point.new(x: 1, y: 2)
good.x # => 1
bad = Point.new(x: "1", y: nil)
# => raises ArgumentError, "x must ..."
Fancier Usage
Stop. Go use Virtus.
Installation
Add the following to your application's Gemfile:
gem 'hash_initialized_struct'
And then run bundle install
.
Contributing
- Fork it ( https://github.com/damncabbage/hash_initialized_struct/fork )
- 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 a new Pull Request
License
See LICENSE.txt