Sha256: 4572f959ecbbaf675ef529ecb2ab9c54661c6fec758f4a0671fcad4b72d931f6

Contents?: true

Size: 902 Bytes

Versions: 2

Compression:

Stored size: 902 Bytes

Contents

module NxtSchema
  module Validators
    class Attribute < Validator
      def initialize(method, expectation)
        @method = method
        @expectation = expectation
      end

      register_as :attribute, :attr
      attr_reader :method, :expectation

      # Query any attribute on a value with validator(:attribute, :size, ->(s) { s < 7 })

      def build
        lambda do |application, value|
          raise ArgumentError, "#{value} does not respond to query: #{method}" unless value.respond_to?(method)

          if expectation.call(value.send(method))
            true
          else
            application.add_error(
              translate_error(
                application.locale,
                attribute: value,
                attribute_name: method,
                value: value.send(method)
              )
            )
          end
        end
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
nxt_schema-1.0.1 lib/nxt_schema/validators/attribute.rb
nxt_schema-1.0.0 lib/nxt_schema/validators/attribute.rb