class Stannum::Schema
Abstract class for defining attribute methods for a struct.
@see Stannum::Attribute
.
Public Class Methods
new()
click to toggle source
Calls superclass method
# File lib/stannum/schema.rb, line 15 def initialize super @attributes = {} end
Public Instance Methods
[](key)
click to toggle source
Retrieves the named attribute object.
@param key [String, Symbol] The name of the requested attribute.
@return [Stannum::Attribute] The attribute object.
@raise ArgumentError if the key is invalid. @raise KeyError if the attribute is not defined.
# File lib/stannum/schema.rb, line 50 def [](key) validate_key(key) attributes.fetch(key.to_s) end
define_attribute(name:, options:, type:)
click to toggle source
@api private
Defines an attribute and adds the attribute to the contract.
This method should not be called directly. Instead, define attributes via the Struct.attribute class method.
@see Stannum::Struct
# File lib/stannum/schema.rb, line 66 def define_attribute(name:, options:, type:) attribute = Stannum::Attribute.new( name: name, options: options, type: type ) if @attributes.key?(attribute.name) raise ArgumentError, "attribute #{name.inspect} already exists" end define_reader(attribute.name, attribute.reader_name) define_writer(attribute.name, attribute.writer_name, attribute.default) @attributes[attribute.name] = attribute end
key?(key)
click to toggle source
Checks if the given attribute is defined.
@param key [String, Symbol] the name of the attribute to check.
@return [Boolean] true if the attribute is defined; otherwise false.
# File lib/stannum/schema.rb, line 89 def key?(key) validate_key(key) attributes.key?(key.to_s) end
Also aliased as: has_key?
own_attributes()
click to toggle source
@private
# File lib/stannum/schema.rb, line 97 def own_attributes @attributes end
Private Instance Methods
attributes()
click to toggle source
# File lib/stannum/schema.rb, line 103 def attributes ancestors .reverse_each .select { |mod| mod.is_a?(Stannum::Schema) } .map(&:own_attributes) .reduce(&:merge) end
define_reader(attr_name, reader_name)
click to toggle source
# File lib/stannum/schema.rb, line 111 def define_reader(attr_name, reader_name) define_method(reader_name) { @attributes[attr_name] } end
define_writer(attr_name, writer_name, default_value)
click to toggle source
# File lib/stannum/schema.rb, line 115 def define_writer(attr_name, writer_name, default_value) define_method(writer_name) do |value| @attributes[attr_name] = value.nil? ? default_value : value end end
validate_key(key)
click to toggle source
# File lib/stannum/schema.rb, line 121 def validate_key(key) raise ArgumentError, "key can't be blank" if key.nil? unless key.is_a?(String) || key.is_a?(Symbol) raise ArgumentError, 'key must be a String or Symbol' end raise ArgumentError, "key can't be blank" if key.to_s.empty? end