class Alphred::Struct
Attributes
attributes[R]
Public Class Methods
attribute(name, **options)
click to toggle source
# 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
attributes()
click to toggle source
# File lib/alphred/struct.rb, line 17 def self.attributes return @attributes if defined?(@attributes) @attributes = [] end
new(**input)
click to toggle source
# 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
Public Instance Methods
to_json(options=nil)
click to toggle source
# File lib/alphred/struct.rb, line 34 def to_json(options=nil) attributes.to_json(options) end
Private Instance Methods
validate_input(input)
click to toggle source
# File lib/alphred/struct.rb, line 40 def validate_input(input) attribute_names = self.class.attributes.map(&:name) invalid_keys = input.keys.reject {|key| attribute_names.include?(key) } unless invalid_keys.empty? msg = "Invalid attribute(s): #{invalid_keys.join(', ')}" raise InvalidAttributeError.new(msg) end end