Sha256: ab3c2e9c474d092cf2817970edadfcccb1c125d4b0750f51592b03f3c5678a7f

Contents?: true

Size: 1.46 KB

Versions: 11

Compression:

Stored size: 1.46 KB

Contents

module Attributor
  class String
    include Type

    def self.native_type
      ::String
    end

    def self.load(value, context = Attributor::DEFAULT_ROOT_CONTEXT, **options)
      if value.is_a?(Enumerable)
        raise IncompatibleTypeError.new(context: context, value_type: value.class, type: self)
      end

      value && String(value)
    rescue
      super
    end

    def self.example(_context = nil, options: {})
      if options[:regexp]
        begin
          # It may fail to generate an example, see bug #72.
          options[:regexp].gen
        rescue => e
          format('Failed to generate example for %s : %s', options[:regexp].inspect, e.message)
        end
      else
        /\w+/.gen
      end
    end

    def self.family
      'string'
    end

    def self.json_schema_type
      :string
    end
    
    # TODO: we're passing the attribute options for now...might need to rethink ...although these are type-specific...
    # TODO: multipleOf, minimum, maximum, exclusiveMinimum and exclusiveMaximum
    def self.as_json_schema( shallow: false, example: nil, attribute_options: {} )
      h = super
      opts = ( self.respond_to?(:options) ) ? self.options.merge( attribute_options ) : attribute_options
      h[:pattern] = self.human_readable_regexp(opts[:regexp]) if opts[:regexp]
      # TODO: minLength, maxLength
      h
    end

    def self.human_readable_regexp( reg )
      return $1 if reg.to_s =~ /\(\?[^:]+:(.+)\)/
      reg
    end
  end
end

Version data entries

11 entries across 11 versions & 1 rubygems

Version Path
attributor-7.1 lib/attributor/types/string.rb
attributor-7.0 lib/attributor/types/string.rb
attributor-6.5 lib/attributor/types/string.rb
attributor-6.4 lib/attributor/types/string.rb
attributor-6.3 lib/attributor/types/string.rb
attributor-6.2 lib/attributor/types/string.rb
attributor-6.1 lib/attributor/types/string.rb
attributor-6.0 lib/attributor/types/string.rb
attributor-5.7 lib/attributor/types/string.rb
attributor-5.6 lib/attributor/types/string.rb
attributor-5.5 lib/attributor/types/string.rb