Sha256: 7198307537a71c75c7c5105507eec9f448a3af204cb4909f105f618f8d58d706

Contents?: true

Size: 1.49 KB

Versions: 11

Compression:

Stored size: 1.49 KB

Contents

# frozen_string_literal: true

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

11 entries across 11 versions & 1 rubygems

Version Path
parametric-0.2.21 lib/parametric/default_types.rb
parametric-0.2.20 lib/parametric/default_types.rb
parametric-0.2.19 lib/parametric/default_types.rb
parametric-0.2.18 lib/parametric/default_types.rb
parametric-0.2.17 lib/parametric/default_types.rb
parametric-0.2.16 lib/parametric/default_types.rb
parametric-0.2.15 lib/parametric/default_types.rb
parametric-0.2.14 lib/parametric/default_types.rb
parametric-0.2.13 lib/parametric/default_types.rb
parametric-0.2.12 lib/parametric/default_types.rb
parametric-0.2.11 lib/parametric/default_types.rb