module DefaultValueFor::ClassMethods
Public Instance Methods
default_value_for(attribute, options = {}, &block)
click to toggle source
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.
# 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)
click to toggle source
# 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