Class: Stannum::Attribute
- Inherits:
-
Object
- Object
- Stannum::Attribute
- Includes:
- Support::Optional
- Defined in:
- lib/stannum/attribute.rb
Overview
Data object representing an attribute on a struct.
Instance Attribute Summary collapse
-
#name ⇒ String
readonly
The name of the attribute.
-
#options ⇒ Hash
readonly
The attribute options.
-
#type ⇒ String
readonly
The name of the attribute type Class or Module.
Instance Method Summary collapse
-
#default ⇒ Object
The default value for the attribute, if any.
-
#default? ⇒ Boolean
True if the attribute has a default value; otherwise false.
-
#initialize(name:, options:, type:) ⇒ Attribute
constructor
A new instance of Attribute.
-
#reader_name ⇒ Symbol
The name of the reader method for the attribute.
-
#resolved_type ⇒ Module
The type of the attribute.
-
#writer_name ⇒ Symbol
The name of the writer method for the attribute.
Methods included from Support::Optional
#optional?, #required?, resolve
Constructor Details
#initialize(name:, options:, type:) ⇒ Attribute
Returns a new instance of Attribute.
17 18 19 20 21 22 23 24 25 26 27 |
# File 'lib/stannum/attribute.rb', line 17 def initialize(name:, options:, type:) validate_name(name) () validate_type(type) @name = name.to_s @options = tools.hash_tools.convert_keys_to_symbols( || {}) @options = resolve_required_option(**@options) @type, @resolved_type = resolve_type(type) end |
Instance Attribute Details
#name ⇒ String (readonly)
Returns the name of the attribute.
30 31 32 |
# File 'lib/stannum/attribute.rb', line 30 def name @name end |
#options ⇒ Hash (readonly)
Returns the attribute options.
33 34 35 |
# File 'lib/stannum/attribute.rb', line 33 def @options end |
#type ⇒ String (readonly)
Returns the name of the attribute type Class or Module.
36 37 38 |
# File 'lib/stannum/attribute.rb', line 36 def type @type end |
Instance Method Details
#default ⇒ Object
Returns the default value for the attribute, if any.
39 40 41 |
# File 'lib/stannum/attribute.rb', line 39 def default @options[:default] end |
#default? ⇒ Boolean
Returns true if the attribute has a default value; otherwise false.
45 46 47 |
# File 'lib/stannum/attribute.rb', line 45 def default? !@options[:default].nil? end |
#reader_name ⇒ Symbol
Returns the name of the reader method for the attribute.
50 51 52 |
# File 'lib/stannum/attribute.rb', line 50 def reader_name @reader_name ||= name.intern end |
#resolved_type ⇒ Module
Returns the type of the attribute.
55 56 57 58 59 60 61 62 63 64 65 |
# File 'lib/stannum/attribute.rb', line 55 def resolved_type return @resolved_type if @resolved_type @resolved_type = Object.const_get(type) unless @resolved_type.is_a?(Module) raise NameError, "constant #{type} is not a Class or Module" end @resolved_type end |
#writer_name ⇒ Symbol
Returns the name of the writer method for the attribute.
68 69 70 |
# File 'lib/stannum/attribute.rb', line 68 def writer_name @writer_name ||= :"#{name}=" end |