Module: DataMapper::Is::CounterCacheable::ClassMethods

Defined in:
lib/dm-is-counter_cacheable/is/counter_cacheable.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#counter_cacheObject (readonly)

Returns the value of attribute counter_cache.



13
14
15
# File 'lib/dm-is-counter_cacheable/is/counter_cacheable.rb', line 13

def counter_cache
  @counter_cache
end

Instance Method Details

#counter_cacheable(relationship_name, options = {}) ⇒ DataMapper::Property

Adds a counter cache property to a related model.

Parameters:

  • relationship_name (Symbol)

    The name of the related model.

  • options (Hash) (defaults to: {})

    Additional options.

Options Hash (options):

  • :counter_property (Symbol)

    The optional property name to store the counter cache in.

  • :counter_index (Boolean)

    Specifies to store the current count in newly created resources.

Returns:

  • (DataMapper::Property)

    The newly added counter cache property.



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/dm-is-counter_cacheable/is/counter_cacheable.rb', line 33

def counter_cacheable(relationship_name,options={})
  @counter_cache ||= []

  unless self.relationships.named?(relationship_name)
    raise(RuntimeError,"unknown relationship #{relationship_name} in #{self}",caller)
  end

  model_name = DataMapper::NamingConventions::Resource::UnderscoredAndPluralized.call(self.name.split('::').last)
  counter_property = if options.has_key?(:counter_property)
                       options[:counter_property]
                     else
                       :"#{model_name}_counter"
                     end

  relationship = self.relationships[relationship_name]
  parent_model = case relationship
                 when DataMapper::Associations::ManyToOne::Relationship,
                      DataMapper::Associations::OneToOne::Relationship
                   relationship.parent_model
                 end

  parent_model.property counter_property, Integer, :default => 0, :min => 0

  if options[:counter_index]
    counter_index = :"#{relationship_name}_#{model_name}_index"

    self.property counter_index, Integer, :min => 1
  else
    counter_index = nil
  end

  @counter_cache << {
    :relationship => relationship_name,
    :counter_property => counter_property,
    :counter_index => counter_index
  }
end