Sha256: 103dbe9247fbab4cc264232be961d6ec13e01cddcfe28349e67c2114a498d2a7

Contents?: true

Size: 1.12 KB

Versions: 1

Compression:

Stored size: 1.12 KB

Contents

# frozen_string_literal: true

module Immoscout
  module Models
    class Base
      attr_reader :base

      def initialize(hash = {})
        define_singleton_method(:base) { hash }
        set_properties
      end

      private

      def prepared_hash
        base
          .deep_stringify_keys
          .deep_transform_keys(&:underscore)
          .deep_symbolize_keys
      end

      def set_properties
        prepared_hash.each do |key, value|
          property = self.class.find_property(key)
          unless property
            # TODO: add optional logger
            # puts "#{self.class.name} - missing property '#{key}'"
            next
          end

          set_property(property, key, value)
        end
      end

      def set_property(property, key, value)
        coerce_klass = property.fetch(:coerce, nil)
        if coerce_klass
          if property.fetch(:array, false)
            send("#{key}=", value.map { |elem| coerce_klass.new(elem) })
          else
            send("#{key}=", coerce_klass.new(value))
          end
        else
          send("#{key}=", value)
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
immoscout-1.3.2 lib/immoscout/models/base.rb