Sha256: 8dea23036b3f30ed784b0b56e29fb88371293a19caca24c921a8b9b91f0f446a

Contents?: true

Size: 779 Bytes

Versions: 2

Compression:

Stored size: 779 Bytes

Contents

class Key

  attr_accessor :name

  def initialize(*args)
    @options = args.last.is_a?(Hash) ? args.pop : {}
    @name, @type = args.shift.to_s, args.shift || Object
    @default_value = @options.delete(:default)
    @options = nil if @type.method(:typecast).arity == 1
  end

  def typecast(value)
    if value.is_a?(Array)
      array = value.map { |v| typecast(v) }.compact
      array.any? ? array : nil
    elsif value.nil? || (value.respond_to?(:empty?) && value.empty?)
      nil
    else
      @options ? @type.typecast(value, @options) : @type.typecast(value)
    end
  end

  def default_value
    value = @default_value.is_a?(Proc) ? @default_value.call : @default_value
    @type.typecast(value)
  end

  def to_s
    "#<Key: name=#{name}, type=#{type}>"
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
presenter-0.1.1 lib/presenter/key.rb
presenter-0.1.0 lib/presenter/key.rb