Sha256: b3fdec9b928ba376a5f13dd14b3707ee39fcc3ade83fb69a62e0728eea988112

Contents?: true

Size: 1.68 KB

Versions: 11

Compression:

Stored size: 1.68 KB

Contents

# Represents a href type.
require 'uri'

module Attributor
  class URI
    include Attributor::Type

    def self.family
      String.family
    end

    def self.valid_type?(value)
      case value
      when ::String, ::URI::Generic
        true
      else
        false
      end
    end

    def self.native_type
      ::URI::Generic
    end

    def self.json_schema_type
      :string
    end

    def self.json_schema_string_format
      :uri
    end

    def self.example(_context = nil, options: {})
      URI(Randgen.uri)
    end

    def self.load(value, context = Attributor::DEFAULT_ROOT_CONTEXT, **_options)
      return nil if value.nil?
      case value
      when native_type
        value
      when ::String
        URI(value)
      else
        raise CoercionError.new(context: context, from: value.class, to: self, value: value)
      end
    end

    def self.dump(value, **_opts)
      value.to_s
    end

    def self.validate(value, context = Attributor::DEFAULT_ROOT_CONTEXT, attribute)
      errors = []

      if attribute && (definition = attribute.options[:path])
        unless value.path =~ attribute.options[:path]
          errors << "#{Attributor.humanize_context(context)} value (#{value}) does not match path (#{definition.inspect})"
        end
      end
      errors
    end

    def self.check_option!(name, definition)
      case name
      when :path
        unless definition.is_a? ::Regexp
          raise AttributorException, "Value for option :path is not a Regexp object. Got (#{definition.inspect})"
        end
        :ok
      else
        :unknown
      end
    end
  end
end

class Randgen
  def self.uri
    "http://example.com/#{word}/#{rand(10**9)}"
  end
end

Version data entries

11 entries across 11 versions & 1 rubygems

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