Class: Struct
- Inherits:
-
Object
- Object
- Struct
- Defined in:
- lib/casual_support/struct/from_h.rb,
lib/casual_support/struct/assign_attributes.rb
Class Method Summary collapse
-
.from_h(attributes) ⇒ self.new
Constructs an instance of a subclass of Struct, and assigns the values of the given attribute Hash to the instance.
Instance Method Summary collapse
-
#assign_attributes(new_attributes) ⇒ self
Assigns values in the given Hash to corresponding attributes of the Struct.
Class Method Details
.from_h(attributes) ⇒ self.new
Constructs an instance of a subclass of Struct, and assigns the values of the given attribute Hash to the instance. This method is intended for use only with subclasses of Struct which do not alter the default signature of the initialize
method. See also #assign_attributes.
17 18 19 20 |
# File 'lib/casual_support/struct/from_h.rb', line 17 def self.from_h(attributes) raise "Struct.from_h is for use only with subclasses of Struct" if self == Struct self.new.assign_attributes(attributes) end |
Instance Method Details
#assign_attributes(new_attributes) ⇒ self
Assigns values in the given Hash to corresponding attributes of the Struct. Both Symbol keys and String keys are accepted. Keys which don’t correspond to an attribute of the Struct are ignored. Mutates the Struct and returns it.
17 18 19 20 21 22 23 24 |
# File 'lib/casual_support/struct/assign_attributes.rb', line 17 def assign_attributes(new_attributes) ms = self.members new_attributes.each do |k, v| m = k.to_sym self[m] = v if ms.include?(m) end self end |