Module: Hashmake::HashMakeable
- Defined in:
- lib/hashmake/hash_makeable.rb
Overview
This module should be included for any class that wants to be ‘hash-makeable’, which means that a new object instance expects all its arguments to come in a single Hash. See the hash_make method in this module and the ArgSpec class for more details.
Defined Under Namespace
Modules: ClassMethods
Class Method Summary collapse
-
.included(base) ⇒ Object
Use the included hook to also extend the including class with HashMake class methods.
Instance Method Summary collapse
-
#find_arg_specs ⇒ Object
Look in the current class for a constant that is a Hash containing (only) ArgSpec objects.
-
#hash_make(hashed_args, arg_specs = find_arg_specs, assign_args = true) ⇒ Object
Process a hash that contains ‘hashed args’.
Class Method Details
.included(base) ⇒ Object
Use the included hook to also extend the including class with HashMake class methods
16 17 18 |
# File 'lib/hashmake/hash_makeable.rb', line 16 def self.included(base) base.extend(ClassMethods) end |
Instance Method Details
#find_arg_specs ⇒ Object
Look in the current class for a constant that is a Hash containing (only) ArgSpec objects. Returns the first constant matching this criteria, or nil if none was found.
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 |
# File 'lib/hashmake/hash_makeable.rb', line 61 def find_arg_specs self.class.constants.each do |constant| val = self.class.const_get(constant) if val.is_a? Hash all_arg_specs = true val.each do |key,value| unless value.is_a? ArgSpec or value.is_a? ArrayArgSpec or value.is_a?(HashArgSpec) all_arg_specs = false break end end if all_arg_specs return val end end end return nil end |
#hash_make(hashed_args, arg_specs = find_arg_specs, assign_args = true) ⇒ Object
Process a hash that contains ‘hashed args’. Each hashed arg is intended to be used in initializing an object instance.
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
# File 'lib/hashmake/hash_makeable.rb', line 34 def hash_make hashed_args, arg_specs = find_arg_specs, assign_args = true arg_specs.each do |key, arg_spec| if hashed_args.has_key?(key) val = hashed_args[key] else if arg_spec.reqd raise ArgumentError, "hashed_args does not have required key #{key}" else if arg_spec.default.is_a?(Proc) && arg_spec.type != Proc val = arg_spec.default.call else val = arg_spec.default end end end arg_spec.validate_value val if assign_args self.instance_variable_set("@#{key.to_s}".to_sym, val) end end end |