lib/gorillib/receiver.rb in gorillib-0.1.4 vs lib/gorillib/receiver.rb in gorillib-0.1.5

- old
+ new

@@ -1,8 +1,9 @@ require 'gorillib/object/blank' require 'gorillib/object/try' require 'gorillib/array/extract_options' +require 'gorillib/metaprogramming/class_attribute' # dummy type for receiving True or False class Boolean ; end unless defined?(Boolean) # Receiver lets you describe complex (even recursive!) actively-typed data models that @@ -124,11 +125,11 @@ # # modify object in place with new typecast values. # def receive! hsh={} raise ArgumentError, "Can't receive (it isn't hashlike): {#{hsh.inspect}}" unless hsh.respond_to?(:[]) && hsh.respond_to?(:has_key?) - self.class.receiver_attr_names.each do |attr| + _receiver_fields.each do |attr| if hsh.has_key?(attr.to_sym) then val = hsh[attr.to_sym] elsif hsh.has_key?(attr.to_s) then val = hsh[attr.to_s] else next ; end _receive_attr attr, val end @@ -151,12 +152,24 @@ def _receive_attr attr, val self.send("receive_#{attr}", val) end + def _receiver_fields + self.class.receiver_attr_names + end + + def _receiver_defaults + self.class.receiver_defaults + end + + def _after_receivers + self.class.after_receivers + end + def impose_defaults!(hsh) - self.class.receiver_defaults.each do |attr, val| + _receiver_defaults.each do |attr, val| next if attr_set?(attr) self.instance_variable_set "@#{attr}", val end end @@ -178,11 +191,11 @@ end end def run_after_receivers(hsh) - self.class.after_receivers.each do |after_receiver| + _after_receivers.each do |after_receiver| self.instance_exec(hsh, &after_receiver) end end public @@ -190,17 +203,18 @@ module ClassMethods # # Returns a new instance with the given hash used to set all rcvrs. # - # All args after the first are passed to the initializer. + # All args up to the last one are passed to the initializer. + # The last arg must be a hash -- its attributes are set on the newly-created object # - # @param hsh [Hash] attr-value pairs to set on the newly created object + # @param hsh [Hash] attr-value pairs to set on the newly created object. # @param *args [Array] arguments to pass to the constructor # @return [Object] a new instance def receive *args - hsh = args.extract_options! + hsh = args.pop raise ArgumentError, "Can't receive (it isn't hashlike): {#{hsh.inspect}} -- the hsh should be the *last* arg" unless hsh.respond_to?(:[]) && hsh.respond_to?(:has_key?) obj = self.new(*args) obj.receive!(hsh) end @@ -382,6 +396,7 @@ self.after_receivers = [] # blocks to execute following receive! extend ClassMethods end end end + end