Class: Simple::SQL::Helpers::RowConverter::StructConverter

Inherits:
Object
  • Object
show all
Defined in:
lib/simple/sql/helpers/row_converter.rb

Overview

:nodoc:

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attributes:, associations:) ⇒ StructConverter

Returns a new instance of StructConverter.



59
60
61
62
63
64
65
# File 'lib/simple/sql/helpers/row_converter.rb', line 59

def initialize(attributes:, associations:)
  @attributes          = attributes
  @associations        = associations
  @association_indices = associations.map { |association| attributes.index(association) } if associations

  @klass = Struct.new(*attributes)
end

Class Method Details

.for(attributes:, associations:) ⇒ Object



54
55
56
57
# File 'lib/simple/sql/helpers/row_converter.rb', line 54

def self.for(attributes:, associations:)
  @cache ||= {}
  @cache[[attributes, associations]] ||= new(attributes: attributes, associations: associations)
end

Instance Method Details

#convert_associations(values) ⇒ Object

convert values at the @association_indices.



75
76
77
78
79
80
81
82
83
# File 'lib/simple/sql/helpers/row_converter.rb', line 75

def convert_associations(values)
  @association_indices.each do |idx|
    value = values[idx]
    case value
    when Hash   then values[idx] = SELF.convert(value, into: :struct)
    when Array  then values[idx] = SELF.convert_row(value, into: :struct)
    end
  end
end

#convert_row(hsh) ⇒ Object



67
68
69
70
71
72
# File 'lib/simple/sql/helpers/row_converter.rb', line 67

def convert_row(hsh)
  values = hsh.values_at(*@attributes)

  convert_associations(values) if @associations
  @klass.new(*values)
end