Module: DefaultValueFor::ClassMethods

Defined in:
lib/default_value_for.rb

Instance Method Summary collapse

Instance Method Details

#default_value_for(attribute, options = {}, &block) ⇒ Object

Declares a default value for the given attribute.

Sets the default value to the given options parameter unless the given options equal { :value => … }

The options can be used to specify the following things:

  • value - Sets the default value.

  • allows_nil (default: true) - Sets explicitly passed nil values if option is set to true.



58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/default_value_for.rb', line 58

def default_value_for(attribute, options = {}, &block)
  value = options.is_a?(Hash) && options.stringify_keys.has_key?('value') ? options.stringify_keys['value'] : options
  allows_nil = options.is_a?(Hash) && options.stringify_keys.has_key?('allows_nil') ? options.stringify_keys['allows_nil'] : true

  if !method_defined?(:set_default_values)
    include(InstanceMethods)

    after_initialize :set_default_values

    if respond_to?(:class_attribute)
      class_attribute :_default_attribute_values
      class_attribute :_default_attribute_values_not_allowing_nil
    else
      class_inheritable_accessor :_default_attribute_values
      class_inheritable_accessor :_default_attribute_values_not_allowing_nil
    end

    extend(DelayedClassMethods)
    init_hash = true
  else
    methods = singleton_methods(false)
    init_hash = !methods.include?("_default_attribute_values") && !methods.include?(:_default_attribute_values)
  end
  if init_hash
    self._default_attribute_values = ActiveSupport::OrderedHash.new
    self._default_attribute_values_not_allowing_nil = []
  end
  if block_given?
    container = BlockValueContainer.new(block)
  else
    container = NormalValueContainer.new(value)
  end
  _default_attribute_values[attribute.to_s] = container
  _default_attribute_values_not_allowing_nil << attribute.to_s unless allows_nil
end

#default_values(values) ⇒ Object



94
95
96
97
98
99
100
101
102
103
104
105
106
# File 'lib/default_value_for.rb', line 94

def default_values(values)
  values.each_pair do |key, options|
    options = options.stringify_keys if options.is_a?(Hash)

    value = options.is_a?(Hash) && options.has_key?('value') ? options['value'] : options

    if value.kind_of? Proc
      default_value_for(key, options.is_a?(Hash) ? options : {}, &value)
    else
      default_value_for(key, options)
    end
  end
end