Class: Stannum::Attribute

Inherits:
Object
  • Object
show all
Includes:
Support::Optional
Defined in:
lib/stannum/attribute.rb

Overview

Data object representing an attribute on an entity.

Defined Under Namespace

Classes: Builder

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Support::Optional

#optional?, #required?, resolve

Constructor Details

#initialize(name:, options:, type:) ⇒ Attribute

Returns a new instance of Attribute.

Options Hash (options:):

  • :default (Object)

    The default value for the attribute. Defaults to nil.

  • :primary_key (Boolean)

    true if the attribute represents the primary key for the entity; otherwise false. Defaults to false.



72
73
74
75
76
77
78
79
80
81
82
# File 'lib/stannum/attribute.rb', line 72

def initialize(name:, options:, type:)
  validate_name(name)
  validate_options(options)
  validate_type(type)

  @name    = name.to_s
  @options = tools.hash_tools.convert_keys_to_symbols(options || {})
  @options = resolve_required_option(**@options)

  @type, @resolved_type = resolve_type(type)
end

Instance Attribute Details

#nameString (readonly)



85
86
87
# File 'lib/stannum/attribute.rb', line 85

def name
  @name
end

#optionsHash (readonly)



88
89
90
# File 'lib/stannum/attribute.rb', line 88

def options
  @options
end

#typeString (readonly)



91
92
93
# File 'lib/stannum/attribute.rb', line 91

def type
  @type
end

Instance Method Details

#association_nameString



95
96
97
# File 'lib/stannum/attribute.rb', line 95

def association_name
  @options[:association_name]
end

#defaultObject



100
101
102
# File 'lib/stannum/attribute.rb', line 100

def default
  @options[:default]
end

#default?Boolean



106
107
108
# File 'lib/stannum/attribute.rb', line 106

def default?
  !@options[:default].nil?
end

#default_value_for(context) ⇒ Object



115
116
117
118
119
# File 'lib/stannum/attribute.rb', line 115

def default_value_for(context)
  return default unless default.is_a?(Proc)

  default.arity.zero? ? default.call : default.call(context)
end

#foreign_key?Boolean



123
124
125
# File 'lib/stannum/attribute.rb', line 123

def foreign_key?
  !!@options[:foreign_key]
end

#primary_key?Boolean



129
130
131
# File 'lib/stannum/attribute.rb', line 129

def primary_key?
  !!@options[:primary_key]
end

#reader_nameSymbol



134
135
136
# File 'lib/stannum/attribute.rb', line 134

def reader_name
  @reader_name ||= name.intern
end

#resolved_typeModule



139
140
141
142
143
144
145
146
147
148
149
# File 'lib/stannum/attribute.rb', line 139

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_nameSymbol



152
153
154
# File 'lib/stannum/attribute.rb', line 152

def writer_name
  @writer_name ||= :"#{name}="
end