Make hash-based object initialization easy!
The hash_make method checks hashed arguments against a set of specifications, then values are assigned to instance variables matching the arg keys.
Type checking via Object#is_a?. The default type is Object, allowing anything. Can allow multiple types. Mark as required/not. Set to true, by default. Default value, for non-required args that aren’t given. For default values that are mutable, make the default value a Proc that can be called to generate the mutable value. Validation of values via a Proc.
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), :z => arg_spec_array(:reqd => false, :type => String, :validator => ->(a){ a.size > 0 }) } attr_reader :x, :y, :z 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 a = MyClass.new :x => 0.5, :z => ["abc", "efg"] # OK a = MyClass.new :x => 0.5, :z => ["abc", ""] # raise ArgumentError, because validator requires str.size > 0 class MultitypeDemo include Hashmake::HashMakeable ARG_SPECS = { :str_or_class => arg_spec(:reqd => true, :type => [String, Class]) } end MultitypeDemo.new(:str_or_class => "") # OK MultitypeDemo.new(:str_or_class => String) # OK MultitypeDemo.new(:str_or_class => 1) # raise ArgumentError
$ gem install hashmake
Copyright © 2013 James Tunnell
See LICENSE.txt for details.