Module: AttrDefault::ClassMethods

Defined in:
lib/attr_default.rb

Instance Method Summary collapse

Instance Method Details

#_attr_defaultsObject



42
43
44
# File 'lib/attr_default.rb', line 42

def _attr_defaults
  @_attr_defaults ||= (superclass._attr_defaults.dup rescue nil) || {}
end

#attr_default(attr_name, default) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/attr_default.rb', line 5

def attr_default attr_name, default
  if !method_defined?(:_attr_default_set)
    include AttrDefault::InstanceMethods
  end

  attr_name = attr_name.to_s
  _attr_defaults[attr_name] = default

  define_method(attr_name) do
    if new_record? && !@_attr_defaults_set_from_dup && !_attr_default_set[attr_name]
      reset_to_default_value(attr_name)
    end
    read_attribute(attr_name)
  end

  define_method("#{attr_name}=") do |*args|
    _attr_default_set[attr_name] = true
    write_attribute(attr_name, *args)
  end

  touch_proc = lambda { |obj| obj.send(attr_name); true }
  before_validation   touch_proc
  before_save         touch_proc
end

#field_added(name, type, args, options) ⇒ Object

Hobo Fields field declaration



31
32
33
34
35
36
37
38
39
40
# File 'lib/attr_default.rb', line 31

def field_added(name, type, args, options)
  if (default = options[:ruby_default])
    attr_default name, default
  elsif (default = options[:default]) && default.is_a?(Proc)
    ActiveSupport::Deprecation.warn(':default => Proc has been deprecated. Use :ruby_default.', caller)
    attr_default name, default
    options.delete(:default)
    options[:ruby_default] = default
  end
end