Class: Nazrin::DataAccessor::Struct

Inherits:
Nazrin::DataAccessor show all
Defined in:
lib/nazrin/data_accessor/struct.rb

Defined Under Namespace

Classes: MissingDomainNameConfigError

Class Attribute Summary collapse

Attributes inherited from Nazrin::DataAccessor

#model, #options

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Nazrin::DataAccessor

accessor_for, accessors, for, #initialize, register, register_accessor, registered_accessor_for, #results

Constructor Details

This class inherits a constructor from Nazrin::DataAccessor

Class Attribute Details

.configObject (readonly)

Returns the value of attribute config.



9
10
11
# File 'lib/nazrin/data_accessor/struct.rb', line 9

def config
  @config
end

Class Method Details

.[](config) ⇒ Object



11
12
13
14
15
# File 'lib/nazrin/data_accessor/struct.rb', line 11

def [](config)
  Class.new(self).tap do |clazz|
    clazz.instance_variable_set(:@config, config)
  end
end

.field_typesObject



29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/nazrin/data_accessor/struct.rb', line 29

def field_types
  return @field_types if defined?(@field_types)

  response = cloudsearch_client.describe_index_fields(
    domain_name: config.domain_name
  )

  @field_types = response.index_fields.each_with_object({}) do |field, fields|
    name = field.options[:index_field_name]
    type = field.options[:index_field_type]

    fields[name] = type
  end
end

.transform_attributes(attributes) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
# File 'lib/nazrin/data_accessor/struct.rb', line 17

def transform_attributes(attributes)
  attributes.each_with_object({}) do |(name, value), hash|
    type = field_types[name]

    if type.end_with?('array')
      hash[name] = value
    else
      hash[name] = value.first
    end
  end
end

Instance Method Details

#data_from_response(res) ⇒ Object



61
62
63
64
65
66
67
# File 'lib/nazrin/data_accessor/struct.rb', line 61

def data_from_response(res)
  res.data[:hits][:hit].map do |hit|
    self.class.transform_attributes(
      { 'id' => hit[:id] }.merge(hit[:fields] || {})
    )
  end
end

#load_all(data) ⇒ Object



55
56
57
58
59
# File 'lib/nazrin/data_accessor/struct.rb', line 55

def load_all(data)
  data.map do |attributes|
    model.new(attributes)
  end
end