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
# 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

  if respond_to?(:has_defaults_options)
    self.has_defaults_options = has_defaults_options.dup
  else
    if respond_to?(:class_attribute)
      class_attribute :has_defaults_options
    else
      class_inheritable_hash :has_defaults_options
    end
  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

  after_initialize :set_default_attributes
end