Sha256: 362f26dd0d1a8f7c1931951fc5879b142c86df1c54b642448b93ca1f00375137

Contents?: true

Size: 1.44 KB

Versions: 8

Compression:

Stored size: 1.44 KB

Contents

require "date"

module Paradocs
  # type coercions
  Paradocs.policy :integer do
    coerce do |v, k, c|
      v.to_i
    end

    meta_data do
      {type: :integer}
    end
  end

  Paradocs.policy :number do
    coerce do |v, k, c|
      v.to_f
    end

    meta_data do
      {type: :number}
    end
  end

  Paradocs.policy :string do
    coerce do |v, k, c|
      v.to_s
    end

    meta_data do
      {type: :string}
    end
  end

  Paradocs.policy :boolean do
    coerce do |v, k, c|
      !!v
    end

    meta_data do
      {type: :boolean}
    end
  end

  # type validations
  Paradocs.policy :array do
    message do |actual|
      "expects an array, but got #{actual.inspect}"
    end

    validate do |value, key, payload|
      !payload.key?(key) || value.is_a?(Array)
    end

    meta_data do
      {type: :array}
    end
  end

  Paradocs.policy :object do
    message do |actual|
      "expects a hash, but got #{actual.inspect}"
    end

    validate do |value, key, payload|
      !payload.key?(key) ||
        value.respond_to?(:[]) &&
        value.respond_to?(:key?)
    end

    meta_data do
      {type: :object}
    end
  end

  Paradocs.policy :split do
    coerce do |v, k, c|
      v.kind_of?(Array) ? v : v.to_s.split(/\s*,\s*/)
    end

    meta_data do
      {type: :array}
    end
  end

  Paradocs.policy :datetime do
    coerce do |v, k, c|
      DateTime.parse(v.to_s)
    end

    meta_data do
      {type: :datetime}
    end
  end
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
paradocs-1.1.4 lib/paradocs/default_types.rb
paradocs-1.1.3 lib/paradocs/default_types.rb
paradocs-1.1.2 lib/paradocs/default_types.rb
paradocs-1.1.1 lib/paradocs/default_types.rb
paradocs-1.1.0 lib/paradocs/default_types.rb
paradocs-1.0.24 lib/paradocs/default_types.rb
paradocs-1.0.23 lib/paradocs/default_types.rb
paradocs-1.0.22 lib/paradocs/default_types.rb