Module: ActiveRemote::AttributeDefaults

Extended by:
ActiveSupport::Concern
Included in:
Base
Defined in:
lib/active_remote/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.

Examples:

Usage

class Person
  include ActiveRemote::AttributeDefaults

  attribute :first_name, :default => "John"
  attribute :last_name, :default => "Doe"
end

person = Person.new
person.first_name #=> "John"
person.last_name #=> "Doe"

Dynamic Default

class Event
  include ActiveAttr::MassAssignment
  include ActiveRemote::AttributeDefaults

  attribute :start_date
  attribute :end_date, :default => lambda { start_date }
end

event = Event.new(:start_date => Date.parse("2012-01-01"))
event.end_date.to_s #=> "2012-01-01"

Instance Method Summary collapse

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.

Examples:

Usage

class Person
  include ActiveRemote::AttributeDefaults

  attribute :first_name, :default => "John"
end

person = Person.new
person.first_name #=> "John"


56
57
58
59
60
61
62
# File 'lib/active_remote/attribute_defaults.rb', line 56

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 if @attributes[name].nil?
  end
end

#attribute_defaultsObject

Calculates the attribute defaults from the attribute definitions

Examples:

Usage

class Person
  include ActiveAttr::AttributeDefaults

  attribute :first_name, :default => "John"
end

Person.new.attribute_defaults #=> {"first_name"=>"John"}


75
76
77
# File 'lib/active_remote/attribute_defaults.rb', line 75

def attribute_defaults
  attributes_map { |name| _attribute_default name }
end

#initializeObject

Applies attribute default values



81
82
83
84
# File 'lib/active_remote/attribute_defaults.rb', line 81

def initialize(*)
  super
  apply_defaults
end