Module: ManaPotion::Pool::ClassMethods

Defined in:
lib/mana-potion/pool.rb

Instance Method Summary collapse

Instance Method Details

#mana_pool_for(association, limit: 1, period: 1.day) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/mana-potion/pool.rb', line 8

def mana_pool_for(association, limit: 1, period: 1.day)
  before_validation do
    owner = send(association)
    other_side_association = owner
    .class
    .reflect_on_all_associations
    .detect { |r| r.class_name == self.class.name }

    count = owner
    .send(other_side_association.name)
    .where(created_at: period.ago..Time.current)
    .count

    if count >= limit
      errors.add(association, :limit, limit: limit, count: count)
    end
  end
end