Module: HasDefaults::ActiveRecordExt::ClassMethods

Defined in:
lib/has_defaults/active_record_ext.rb

Instance Method Summary collapse

Instance Method Details

#has_defaults(attrs) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/has_defaults/active_record_ext.rb', line 6

def has_defaults(attrs)
  raise "Hash expected; #{attrs.class} given." unless attrs.is_a?(Hash)

  include InstanceMethods

  # Check if our parent class had default options, whose accessor we inherited.
  # In this case we clone the default options as to not modify the options of our parent.
  if respond_to?(:has_defaults_options)
    self.has_defaults_options = has_defaults_options.dup
  else
    # Rails 3 and 2 have different copy-and-write accessor generators.
    if respond_to?(:class_attribute)
      class_attribute :has_defaults_options
    else
      class_inheritable_hash :has_defaults_options
    end
    # We only register the callback if we haven't registered it before,
    # since in this branch we didn't inherit #has_defaults_options
    after_initialize :set_default_attributes
  end

  self.has_defaults_options ||= {}
  self.has_defaults_options.merge!(attrs)

  if Rails.version < '3'
    # ActiveRecord only calls after_initialize callbacks only if is
    # explicit defined in a class. We should however only define that
    # callback if a default has been set, as it really slow downs Rails.
    unless method_defined?(:after_initialize)
      define_method(:after_initialize) {}
    end
  end

end