File: precountable.rb

package info (click to toggle)
ruby-activerecord-precounter 0.4.0-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 140 kB
  • sloc: ruby: 88; makefile: 10; sh: 4
file content (20 lines) | stat: -rw-r--r-- 548 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
module ActiveRecord
  module Precountable
    class NotPrecountedError < StandardError
    end

    def precounts(*association_names)
      association_names.each do |association_name|
        var_name = "#{association_name}_count"
        instance_var_name = "@#{var_name}"

        attr_writer(var_name)
        define_method(var_name) do
          count = instance_variable_get(instance_var_name)
          raise NotPrecountedError.new("`#{association_name}' not precounted") unless count
          count
        end
      end
    end
  end
end