Class: Key
Instance Attribute Summary collapse
-
#name ⇒ Object
Returns the value of attribute name.
Instance Method Summary collapse
- #default_value ⇒ Object
-
#initialize(*args) ⇒ Key
constructor
A new instance of Key.
- #to_s ⇒ Object
- #typecast(value) ⇒ Object
Constructor Details
#initialize(*args) ⇒ Key
Returns a new instance of Key.
5 6 7 8 9 10 |
# File 'lib/presenter/key.rb', line 5 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 |
Instance Attribute Details
#name ⇒ Object
Returns the value of attribute name.
3 4 5 |
# File 'lib/presenter/key.rb', line 3 def name @name end |
Instance Method Details
#default_value ⇒ Object
23 24 25 26 |
# File 'lib/presenter/key.rb', line 23 def default_value value = @default_value.is_a?(Proc) ? @default_value.call : @default_value @type.typecast(value) end |
#to_s ⇒ Object
28 29 30 |
# File 'lib/presenter/key.rb', line 28 def to_s "#<Key: name=#{name}, type=#{type}>" end |
#typecast(value) ⇒ Object
12 13 14 15 16 17 18 19 20 21 |
# File 'lib/presenter/key.rb', line 12 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 |