Module: ActiveRepository::Writers

Included in:
Base
Defined in:
lib/active_repository/writers.rb

Defined Under Namespace

Modules: InstanceMethods

Instance Method Summary collapse

Instance Method Details

#create(attributes = {}) ⇒ Object

Creates an object and persists it.



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/active_repository/writers.rb', line 5

def create(attributes={})
  attributes = attributes.symbolize_keys if attributes.respond_to?(:symbolize_keys)
  object = self.new(attributes)

  if object.present? && object.valid?
    if get_model_class == self
      object.id = nil unless exists?(object.id)

      object.save
    else
      object = PersistenceAdapter.create(self, object.attributes)
    end
  end

  new_object = serialize!(object.reload.attributes)

  new_object.valid?

  new_object
end

#find_or_create(attributes) ⇒ Object

Searches for an object that matches the attributes on the parameter, if none is found it creates one with the defined attributes.



28
29
30
31
32
# File 'lib/active_repository/writers.rb', line 28

def find_or_create(attributes)
  object = where(attributes).first

  object.nil? ? create(attributes) : object
end

#find_or_initialize(attributes) ⇒ Object



34
35
36
37
38
39
40
41
42
43
# File 'lib/active_repository/writers.rb', line 34

def find_or_initialize(attributes)
  object = where(attributes).first
  object = self.new(attributes) if object.nil?

  attributes.each do |key, value|
    object.send("#{key.to_sym}=", value)
  end

  serialize!(object.attributes)
end