hashmake
Description
Make hash-based object initialization easy!
Provides hash_make method that can consider parameter name, type, default value, validation, requiredd/not, and container type (none/array/hash) according to the specification provided. The value is assigned to an instance variable matching the arg key.
There is also a make_hash method to turn an object into a representative Hash object. Any hash-makeable sub-objects can be turned into Hash objects as well.
Features
Examples
require 'hashmake'
class MyClass
include Hashmake::HashMakeable
ARG_SPECS = {
:x => arg_spec(:reqd => true, :type => Float, :validator => ->(a){ a.between?(0.0,1.0) }),
:y => arg_spec(:reqd => false, :type => Float, :validator => ->(a){ a.between?(0.0,1.0) }, :default => 0.0),
}
attr_reader :x, :y
def initialize hashed_args
hash_make(ARG_SPECS, hashed_args)
end
end
a = MyClass.new :x => 0.5 # a.x => 0.5, a.y => 0.0
a = MyClass.new :x => 0.5, :y => 0.2 # a.x => 0.5, a.y => 0.2
a = MyClass.new # raise ArgumentError because :x is reqd and not given
a = MyClass.new :y => 0.5 # raise ArgumentError because :x is reqd and not given
Requirements
Install
$ gem install hashmake
Copyright
Copyright © 2013 James Tunnell
See LICENSE.txt for details.