Module: Toy::Persistence::ClassMethods

Defined in:
lib/toy/persistence.rb

Instance Method Summary collapse

Instance Method Details

#adapter(name = nil, client = nil, options = {}) ⇒ Object

Raises:

  • (ArgumentError)


6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/toy/persistence.rb', line 6

def adapter(name=nil, client=nil, options={})
  missing_client = !name.nil? && client.nil?
  raise(ArgumentError, 'Client is required') if missing_client

  needs_default_adapter = name.nil? && client.nil?
  assigning_adapter     = !name.nil? && !client.nil?

  if needs_default_adapter
    @adapter ||= Adapter[:memory].new({}, options)
  elsif assigning_adapter
    @adapter = Adapter[name].new(client, options)
  end

  @adapter
end

#attribute(*args) ⇒ Object



38
39
40
41
# File 'lib/toy/persistence.rb', line 38

def attribute(*args)
  @persisted_attributes = nil
  super
end

#create(attrs = {}) ⇒ Object



22
23
24
# File 'lib/toy/persistence.rb', line 22

def create(attrs={})
  new(attrs).tap { |doc| doc.save }
end

#delete(*ids) ⇒ Object



26
27
28
# File 'lib/toy/persistence.rb', line 26

def delete(*ids)
  ids.each { |id| get(id).try(:delete) }
end

#destroy(*ids) ⇒ Object



30
31
32
# File 'lib/toy/persistence.rb', line 30

def destroy(*ids)
  ids.each { |id| get(id).try(:destroy) }
end

#persisted_attributesObject



34
35
36
# File 'lib/toy/persistence.rb', line 34

def persisted_attributes
  @persisted_attributes ||= attributes.values.select(&:persisted?)
end