Module: Genesis::ActiveRecordExtensions::ClassMethods

Defined in:
lib/genesis/active_record_extensions.rb

Instance Method Summary collapse

Instance Method Details

#create_or_update(attrs = {}) ⇒ Object



36
37
38
# File 'lib/genesis/active_record_extensions.rb', line 36

def create_or_update( attrs={} )
  self.create_or_update_by( :id, attrs )
end

#create_or_update_by(field, attrs = {}) ⇒ Object



40
41
42
43
44
45
46
47
48
# File 'lib/genesis/active_record_extensions.rb', line 40

def create_or_update_by( field, attrs={} )
  attrs = extract_ar_object_ids( attrs )
  find_value = attrs[field]
  conditions = {field => find_value}
  record = find( :first, :conditions => conditions) || self.new
  record.attributes = attrs
  record.save!
  record
end

#create_or_update_by_all(attrs = {}) ⇒ Object

Use all attributes to try and find a record. If found returns the record. Otherwise creates and returns the record.



12
13
14
15
16
17
18
19
# File 'lib/genesis/active_record_extensions.rb', line 12

def create_or_update_by_all( attrs={} )
  attrs = extract_ar_object_ids( attrs )
  conditions = attrs
  record = find( :first, :conditions => conditions ) || self.new
  record.attributes = attrs
  record.save!
  record
end

#create_or_update_by_some(attrs = {}) ⇒ Object

Use some attributes (the ones passed in as the find_by hash) to try and find a record. If found returns the record. Otherwise creates and returns the record with all of the attributes (including the ones in the find_by hash.)



25
26
27
28
29
30
31
32
33
34
# File 'lib/genesis/active_record_extensions.rb', line 25

def create_or_update_by_some( attrs={} )
  attrs = extract_ar_object_ids( attrs )
  conditions = attrs.delete( :find_by )
  raise 'You must provide a :find_by hash of attributes to search with, ie. :find_by => {:id => 1}' unless conditions
  attrs.merge!( conditions )
  record = find( :first, :conditions => conditions ) || self.new
  record.attributes = attrs
  record.save!
  record
end

#method_missing_with_create_or_update(method_name, *args) ⇒ Object

Catches method missing exceptions and tries to write a custom find or update by method that uses the he field name at the end of the method name as the find conditions. Method must match pattern create_or_update_by_attribute



53
54
55
56
57
58
59
60
# File 'lib/genesis/active_record_extensions.rb', line 53

def method_missing_with_create_or_update( method_name, *args )
  if match = method_name.to_s.match(/create_or_update_by_([a-z0-9_]+)/)
    field = match[1].to_sym
    create_or_update_by(field, *args)
  else
    method_missing_without_create_or_update(method_name, *args)
  end
end