Module: ActiveAttr::AttributeDefaults
- Extended by:
- ActiveSupport::Concern
- Includes:
- Attributes, ChainableInitialization
- Included in:
- Model
- Defined in:
- lib/active_attr/attribute_defaults.rb
Overview
AttributeDefaults allows defaults to be declared for your attributes
Defaults are declared by passing the :default option to the attribute class method. If you need the default to be dynamic, pass a lambda, Proc, or any object that responds to #call as the value to the :default option and the result will calculated on initialization. These dynamic defaults can depend on the values of other attributes when those attributes are assigned using MassAssignment or BlockInitialization.
Instance Method Summary collapse
-
#apply_defaults(defaults = attribute_defaults) ⇒ Object
Applies the attribute defaults.
-
#attribute_defaults ⇒ Hash{String => Object}
Calculates the attribute defaults from the attribute definitions.
-
#initialize ⇒ Object
Applies attribute default values.
Methods included from Attributes
#==, #attributes, filter_attributes, filter_attributes=, #inspect, #read_attribute, #write_attribute
Instance Method Details
#apply_defaults(defaults = attribute_defaults) ⇒ Object
Applies the attribute defaults
Applies all the default values to any attributes not yet set, avoiding any attribute setter logic, such as dirty tracking.
70 71 72 73 74 75 76 |
# File 'lib/active_attr/attribute_defaults.rb', line 70 def apply_defaults(defaults=attribute_defaults) @attributes ||= {} defaults.each do |name, value| # instance variable is used here to avoid any dirty tracking in attribute setter methods @attributes[name] = value unless @attributes.has_key? name end end |
#attribute_defaults ⇒ Hash{String => Object}
Calculates the attribute defaults from the attribute definitions
92 93 94 |
# File 'lib/active_attr/attribute_defaults.rb', line 92 def attribute_defaults attributes_map { |name| _attribute_default name } end |
#initialize ⇒ Object
Applies attribute default values
99 100 101 102 |
# File 'lib/active_attr/attribute_defaults.rb', line 99 def initialize(*) super apply_defaults end |