class Struct
Public Class Methods
from_h(attributes)
click to toggle source
Constructs an instance of a subclass of Struct
, and assigns the values of the given attributes
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. Specifically, the initialize
method must support invocation with no arguments.
@example
Point = Struct.new(:x, :y, :z) Point.from_h(x: 10, y: 20, z: 30) # == Point.new(10, 20, 30)
@param attributes [Hash{Symbol => Object}, Hash{String => Object}] @return [Struct]
# File lib/casual_support/struct/from_h.rb, line 22 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
Public Instance Methods
assign_attributes(new_attributes)
click to toggle source
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.
@example
Point = Struct.new(:x, :y, :z) point = Point.new(10, 20, 30) point.assign_attributes(y: 30, z: 50).to_h # == { x: 10, y: 30, z: 50 }
@param new_attributes [Hash{Symbol => Object}, Hash{String => Object}] @return [self]
# File lib/casual_support/struct/assign_attributes.rb, line 16 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