Module: HasDefaults::ActiveRecordExt::ClassMethods

Defined in:
lib/has_defaults/active_record_ext.rb

Instance Method Summary collapse

Instance Method Details

#has_defaults(attrs) ⇒ Object

Raises:



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/has_defaults/active_record_ext.rb', line 9

def has_defaults(attrs)
  raise Error, "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)
end