Class: FriendlyAttributes::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/friendly_attributes/base.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.find_or_build_by_active_record_id(active_record_id, options = {}) ⇒ FriendlyAttributes::Base

Finds an existing Friendly model, associated with an ActiveRecord model, or builds a new Friendly model, using the specified options.

Parameters:

  • ActiveRecord (Integer)

    model ID for which to find the associated Friendly model

  • options (Hash) (defaults to: {})

Returns:



10
11
12
# File 'lib/friendly_attributes/base.rb', line 10

def find_or_build_by_active_record_id(active_record_id, options={})
  active_record_id && first(active_record_key => active_record_id) || new(options.merge(active_record_key => active_record_id))
end

Instance Method Details

#attributesObject

Alias for Friendly::Document#to_hash



45
46
47
# File 'lib/friendly_attributes/base.rb', line 45

def attributes
  to_hash
end

#read_active_record_idInteger

Get the ID of the associated ActiveRecord model.

Uses the :active_record_key property of the model.

Returns:

  • (Integer)

    ActiveRecord ID



30
31
32
# File 'lib/friendly_attributes/base.rb', line 30

def read_active_record_id
  send(active_record_key)
end

#update_if_changed_with_model(active_record_id) ⇒ true, false

Save the FriendlyAttribute model if it has been changed. Before saving, it sets the specified active_record_id, to handle the case when it is a new record or has been reassigned.

Parameters:

  • active_record_id (Integer)

    ID of the associated ActiveRecord model

Returns:

  • (true, false)

    result of saving the record



39
40
41
42
# File 'lib/friendly_attributes/base.rb', line 39

def update_if_changed_with_model(active_record_id)
  write_active_record_id(active_record_id) unless read_active_record_id == active_record_id
  save if changed?
end

#write_active_record_id(active_record_id) ⇒ String, Integer

Set the ID of the associated ActiveRecord model.

Uses the :active_record_key property of the model.

Parameters:

  • active_record_id (String, Integer)

    value to set the attribute

Returns:

  • (String, Integer)

    value



21
22
23
# File 'lib/friendly_attributes/base.rb', line 21

def write_active_record_id(active_record_id)
  send(:"#{active_record_key}=", active_record_id)
end