Sha256: 7d483ebd77af222804af4fc55f382ba417da331e47ee7899f1b92a1a0dc1ec02

Contents?: true

Size: 1.67 KB

Versions: 2

Compression:

Stored size: 1.67 KB

Contents

require 'aws-sdk-cloudsearch'

module Nazrin
  class DataAccessor
    class Struct < Nazrin::DataAccessor
      class MissingDomainNameConfigError < StandardError; end

      class << self
        attr_reader :config

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

        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

        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

        private

        def cloudsearch_client
          @cloudsearch_client ||= Aws::CloudSearch::Client.new(
            access_key_id: config.access_key_id,
            secret_access_key: config.secret_access_key,
            logger: config.logger
          )
        end
      end

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

      def data_from_response(res)
        res.data[:hits][:hit].map do |hit|
          self.class.transform_attributes(hit[:fields])
        end
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
nazrin-2.6.0 lib/nazrin/data_accessor/struct.rb
nazrin-2.5.0 lib/nazrin/data_accessor/struct.rb