Class: Alphred::Struct

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

Direct Known Subclasses

Icon, Item, Mod, Mods, Text

Defined Under Namespace

Classes: Attribute, InvalidAttributeError, InvalidEnumError, RequiredAttributeError

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(**input) ⇒ Struct

Returns a new instance of Struct.



24
25
26
27
28
29
30
31
32
# File 'lib/alphred/struct.rb', line 24

def initialize(**input)
  validate_input(input)

  @attributes = self.class.attributes.select { |attr|
    attr.required? || input.keys.include?(attr.name)
  }.reduce({}) { |hash, attr|
    hash.merge(attr.value_from(input))
  }
end

Instance Attribute Details

#attributesObject (readonly)

Returns the value of attribute attributes.



22
23
24
# File 'lib/alphred/struct.rb', line 22

def attributes
  @attributes
end

Class Method Details

.attribute(name, **options) ⇒ Object



9
10
11
12
13
14
15
# File 'lib/alphred/struct.rb', line 9

def self.attribute(name, **options)
  attributes << Attribute.new(name, **options)

  define_method(name) do
    attributes[name]
  end
end

.attributesObject



17
18
19
20
# File 'lib/alphred/struct.rb', line 17

def self.attributes
  return @attributes if defined?(@attributes)
  @attributes = []
end

Instance Method Details

#to_json(options = nil) ⇒ Object



34
35
36
# File 'lib/alphred/struct.rb', line 34

def to_json(options=nil)
  attributes.to_json(options)
end