Class: Alphred::Struct::Attribute

Inherits:
Object
  • Object
show all
Defined in:
lib/alphred/struct.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, **options) ⇒ Attribute

Returns a new instance of Attribute.



52
53
54
55
56
57
# File 'lib/alphred/struct.rb', line 52

def initialize(name, **options)
  @name = name
  @required = options.fetch(:required, false)
  @coerce = options.fetch(:coerce, ->(x) { x })
  @enum = options[:enum]
end

Instance Attribute Details

#coerceObject (readonly)

Returns the value of attribute coerce.



50
51
52
# File 'lib/alphred/struct.rb', line 50

def coerce
  @coerce
end

#enumObject (readonly)

Returns the value of attribute enum.



50
51
52
# File 'lib/alphred/struct.rb', line 50

def enum
  @enum
end

#nameObject (readonly)

Returns the value of attribute name.



50
51
52
# File 'lib/alphred/struct.rb', line 50

def name
  @name
end

Instance Method Details

#required?Boolean

Returns:

  • (Boolean)


59
60
61
# File 'lib/alphred/struct.rb', line 59

def required?
  !!@required
end

#value_from(hash) ⇒ Object

Raises:



63
64
65
66
67
68
# File 'lib/alphred/struct.rb', line 63

def value_from(hash)
  uncoerced = hash.fetch(name) { raise RequiredAttributeError.new(name) }
  coerced = coerce.call(uncoerced)
  raise InvalidEnumError.new(coerced) if enum && !enum.include?(coerced)
  { name => coerced }
end