Sha256: 333ae826124b96e3753ac46a203f2f28602a28f207b06cd4d2a02972e6efdcc8

Contents?: true

Size: 1.55 KB

Versions: 7

Compression:

Stored size: 1.55 KB

Contents

# frozen_string_literal: true

class Serega
  module SeregaValidations
    module Initiate
      class CheckModifiers
        class << self
          def call(serializer_class, fields)
            return unless fields

            validate(serializer_class, fields, [])
          end

          private

          def validate(serializer_class, fields, prev_names)
            fields.each do |name, nested_fields|
              attribute = serializer_class.attributes[name]

              raise_error(name, prev_names) unless attribute
              next if nested_fields.empty?

              raise_nested_error(name, prev_names, nested_fields) unless attribute.relation?
              nested_serializer = attribute.serializer
              validate(nested_serializer, nested_fields, prev_names + [name])
            end
          end

          def raise_error(name, prev_names)
            field_name = field_name(name, prev_names)

            raise Serega::AttributeNotExist, "Attribute #{field_name} not exists"
          end

          def raise_nested_error(name, prev_names, nested_fields)
            field_name = field_name(name, prev_names)
            first_nested = nested_fields.keys.first

            raise Serega::AttributeNotExist, "Attribute #{field_name} has no :serializer option specified to add nested '#{first_nested}' attribute"
          end

          def field_name(name, prev_names)
            res = "'#{name}'"
            res += " ('#{prev_names.join(".")}.#{name}')" if prev_names.any?
            res
          end
        end
      end
    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
serega-0.6.1 lib/serega/validations/initiate/check_modifiers.rb
serega-0.6.0 lib/serega/validations/initiate/check_modifiers.rb
serega-0.5.2 lib/serega/validations/initiate/check_modifiers.rb
serega-0.5.1 lib/serega/validations/initiate/check_modifiers.rb
serega-0.5.0 lib/serega/validations/initiate/check_modifiers.rb
serega-0.4.0 lib/serega/validations/initiate/check_modifiers.rb
serega-0.3.0 lib/serega/validations/initiate/check_modifiers.rb