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
93
94
# File 'lib/default_value_for.rb', line 58

def default_value_for(attribute, options = {}, &block)
  value      = options
  allows_nil = true

  if options.is_a?(Hash)
    opts       = options.stringify_keys
    value      = opts.fetch('value', options)
    allows_nil = opts.fetch('allows_nil', true)
  end

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

    after_initialize :set_default_values

    class_attribute :_default_attribute_values
    class_attribute :_default_attribute_values_not_allowing_nil

    extend(DelayedClassMethods)
    init_hash = true
  else
    init_hash = !singleton_methods(false).include?(:_default_attribute_values)
  end

  if init_hash
    self._default_attribute_values = {}
    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



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

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