Sha256: 6ba1417546980587e3691711c9163b98403de0a28c4aaf255c74a2aced618973

Contents?: true

Size: 1.34 KB

Versions: 21

Compression:

Stored size: 1.34 KB

Contents

# frozen_string_literal: true

class ReeMapper::Field
  attr_reader :type, :name, :from, :doc, :optional, :null, :roles, :default,
              :name_as_str, :name_as_instance_var_name, :from_as_str

  NO_DEFAULT = Object.new.freeze

  contract(
    Any,
    Nilor[Symbol],
    Kwargs[
      from:     Nilor[Symbol],
      doc:      Nilor[String],
      optional: Bool,
      null:     Bool,
      role:     Nilor[ArrayOf[Symbol], Symbol],
      default:  Any
    ] => Any
  ).throws(ArgumentError)
  def initialize(type, name = nil, from: nil, doc: nil, optional: false, null: false, role: nil, default: NO_DEFAULT)
    @type     = type
    @name     = name
    @from     = from || name
    @doc      = doc
    @optional = optional
    @null     = null
    @roles    = Array(role)
    @default  = default

    @name_as_str               = @name.to_s
    @name_as_instance_var_name = :"@#{@name}"
    @from_as_str               = @from.to_s

    raise ArgumentError, 'required fields do not support defaults' if has_default? && !optional
  end

  contract None => Bool
  def has_default?
    default != NO_DEFAULT
  end

  contract Nilor[Symbol, ArrayOf[Symbol]] => Bool
  def has_role?(role)
    return true  if roles.empty?
    return false if role.nil?

    if role.is_a?(Array)
      role.any? { roles.include?(_1) }
    else
      roles.include?(role)
    end
  end
end

Version data entries

21 entries across 21 versions & 1 rubygems

Version Path
ree_lib-1.0.0 lib/ree_lib/packages/ree_mapper/package/ree_mapper/field.rb