module PIM::Utils::EnhancedStruct

Public Class Methods

included(struct_class) click to toggle source
# File pim.rb, line 1932
def self.included struct_class
  raise "Class #{struct_class} must be a 'Struct'" unless struct_class < Struct
  struct_class.include GetterSetterAware
  struct_class.extend EnhancedStruct::Internal
end
new(*args) click to toggle source
Calls superclass method
# File pim.rb, line 1856
def initialize *args

  values = args[0]
  if values.is_a?(Hash)

    # Convert values to symbolized hash
    values = PIM::Utils.symbolized_snakeized_hash(values)

    # Handle values, if possible
    handle_initial_values = self.class.instance_variable_get(:@__handle_initial_values)
    handle_initial_values.call(values) unless handle_initial_values.nil?

    # Delete any unknown members
    values.delete_if { |k,v| !struct_members.include?(k) }

    # Convert all date members
    date_members = self.class.instance_variable_get(:@__date_members)
    unless date_members.nil?
      date_members.each do |date_member|
        date = PIM::Utils.to_date(values[date_member])
        next if date.nil?
        values[date_member] = date
      end
    end

    # Apply conversions
    convert_members = self.class.instance_variable_get(:@__convert_members)
    unless convert_members.nil?
      convert_members.each_pair do |member, block|
        value = values[member]
        next if value.nil?
        values[member] = block.call(value)
      end
    end

    args[0] = values

  end

  super *args

end

Public Instance Methods

as_json() click to toggle source
# File pim.rb, line 1938
def as_json

  # Convert values back to "camelized" hash
  PIM::Utils.unsymbolized_camelized_hash(to_h)

end
struct_members() click to toggle source
# File pim.rb, line 1899
def struct_members
  # Directly call defined method in Struct,
  # because 'members' might have been used as a component, e.g. in 'Attribute'!
  self.class.superclass.members
end
to_json(*args) click to toggle source

‘Struct’ cannot be correctly written out as JSON, so convert it to Hash first

# File pim.rb, line 1946
def to_json *args
  as_json.to_json(*args)
end