Class: Anchormodel::Attribute

Inherits:
Object
  • Object
show all
Defined in:
lib/anchormodel/attribute.rb

Overview

This class holds all information related to a Rails model pointing to an Anchormodel. It is instanciated when ModelMixin#belongs_to_anchormodel is used.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(model_class, attribute_name, anchor_class_name = nil, optional = false) ⇒ Attribute

Returns a new instance of Attribute.

Parameters:

  • model_class (ActiveRecord::Base)

    The Rails model where ModelMixin#belongs_to_anchormodel is used

  • attribute_name (String, Symbol)

    The name and database column of the attribute

  • anchor_class_name (String) (defaults to: nil)

    Name of the Anchormodel class (omit if attribute :foo_bar holds an Anchormodels::FooBar)

  • optional (Boolean) (defaults to: false)

    If true, a presence validation is added to the model.



12
13
14
15
16
17
# File 'lib/anchormodel/attribute.rb', line 12

def initialize(model_class, attribute_name, anchor_class_name = nil, optional = false)
  @model_class = model_class
  @attribute_name = attribute_name.to_sym
  @anchor_class_name = anchor_class_name || "Anchormodels::#{attribute_name.to_s.classify}"
  @optional = optional
end

Instance Attribute Details

#attribute_nameObject (readonly)



5
6
7
# File 'lib/anchormodel/attribute.rb', line 5

def attribute_name
  @attribute_name
end

#optionalObject (readonly)



6
7
8
# File 'lib/anchormodel/attribute.rb', line 6

def optional
  @optional
end

Instance Method Details

#anchor_classObject

Getter for the Anchormodel class based on the name passed to the initializer. We are loading the anchor class lazily, because the model mixin instanciates this statically -> avoid premature anchor class loading



21
22
23
# File 'lib/anchormodel/attribute.rb', line 21

def anchor_class
  @anchor_class ||= @anchor_class_name.constantize
end