Sha256: 71ecc296b63fac7ccf9d3c1930c5c6cacbaedb2c2631f94d2518a00e53a91a4c

Contents?: true

Size: 1.46 KB

Versions: 15

Compression:

Stored size: 1.46 KB

Contents

require "date"

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

    meta_data do
      {type: :integer}
    end
  end

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

    meta_data do
      {type: :number}
    end
  end

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

    meta_data do
      {type: :string}
    end
  end

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

    meta_data do
      {type: :boolean}
    end
  end

  # type validations
  Parametric.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

  Parametric.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

  Parametric.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

  Parametric.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

15 entries across 15 versions & 1 rubygems

Version Path
parametric-0.2.10 lib/parametric/default_types.rb
parametric-0.2.9 lib/parametric/default_types.rb
parametric-0.2.8 lib/parametric/default_types.rb
parametric-0.2.7 lib/parametric/default_types.rb
parametric-0.2.6 lib/parametric/default_types.rb
parametric-0.2.5 lib/parametric/default_types.rb
parametric-0.2.4 lib/parametric/default_types.rb
parametric-0.2.3 lib/parametric/default_types.rb
parametric-0.2.2 lib/parametric/default_types.rb
parametric-0.2.1 lib/parametric/default_types.rb
parametric-0.2.0 lib/parametric/default_types.rb
parametric-0.1.3 lib/parametric/default_types.rb
parametric-0.1.2 lib/parametric/default_types.rb
parametric-0.1.1 lib/parametric/default_types.rb
parametric-0.1.0 lib/parametric/default_types.rb