Class: Moodwall::Record

Inherits:
Object
  • Object
show all
Includes:
Comparable
Defined in:
lib/moodwall/record.rb

Direct Known Subclasses

Mood, Wallpaper

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#idObject (readonly)

Returns the value of attribute id.



10
11
12
# File 'lib/moodwall/record.rb', line 10

def id
  @id
end

#repository=(value) ⇒ Object (writeonly)

Sets the attribute repository

Parameters:

  • value

    the value to set the attribute repository to.



9
10
11
# File 'lib/moodwall/record.rb', line 9

def repository=(value)
  @repository = value
end

Class Method Details

.allObject



17
18
19
20
21
# File 'lib/moodwall/record.rb', line 17

def all
  transaction(read_only: true) do |store|
    Array store[name]
  end
end

.find!(id) ⇒ Object



29
30
31
32
# File 'lib/moodwall/record.rb', line 29

def find!(id)
  all.find { |r| r.id == id.to_i } ||
    raise(RecordNotFoundError, "Can't find the record with id: #{ id }")
end

.next_idObject



34
35
36
# File 'lib/moodwall/record.rb', line 34

def next_id
  all.map(&:id).max.to_i + 1
end

.repositoryObject



13
14
15
# File 'lib/moodwall/record.rb', line 13

def repository
  Thread.current[:repository] ||= PStore.new("database.store")
end

.resetObject



23
24
25
26
27
# File 'lib/moodwall/record.rb', line 23

def reset
  transaction do |store|
    store.delete name
  end
end

.transaction(read_only: false, &transaction_body) ⇒ Object



38
39
40
# File 'lib/moodwall/record.rb', line 38

def transaction(read_only: false, &transaction_body)
  repository.transaction(read_only, &transaction_body)
end

Instance Method Details

#==(other) ⇒ Object



43
44
45
# File 'lib/moodwall/record.rb', line 43

def ==(other)
  id == other.id
end

#deleteObject



65
66
67
68
69
70
# File 'lib/moodwall/record.rb', line 65

def delete
  self.class.repository.transaction do |store|
    Array(store[self.class.name]).delete self
  end
  self
end

#new_record?Boolean

Returns:

  • (Boolean)


72
73
74
# File 'lib/moodwall/record.rb', line 72

def new_record?
  @id.nil?
end

#reloadObject



76
77
78
# File 'lib/moodwall/record.rb', line 76

def reload
  self.class.find! @id
end

#saveObject Also known as: save!



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/moodwall/record.rb', line 47

def save
  if new_record?
    @id = self.class.next_id

    transaction do |store|
      store[self.class.name] ||= []
      store[self.class.name] << self
    end
  else
    transaction do |store|
      store[self.class.name].delete_if { |r| r.id == @id }
      store[self.class.name] << self
    end
  end
  self
end