Class: Moodwall::Wallpaper

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

Instance Attribute Summary collapse

Attributes inherited from Record

#id, #repository

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Record

#==, all, #delete, find!, #new_record?, next_id, #reload, repository, reset, transaction

Constructor Details

#initialize(options) ⇒ Wallpaper

Returns a new instance of Wallpaper.



11
12
13
14
15
# File 'lib/moodwall/wallpaper.rb', line 11

def initialize(options)
  @path    = options.fetch(:path) { raise(MissingPathError, "Wallpaper path is required") }
  @mood_id = options.fetch(:mood_id) { Moodwall::Mood.current }
  @weight  = options.fetch(:weight, 0)
end

Instance Attribute Details

#mood_idObject (readonly)

Returns the value of attribute mood_id.



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

def mood_id
  @mood_id
end

#pathObject (readonly)

Returns the value of attribute path.



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

def path
  @path
end

#weightObject (readonly)

Returns the value of attribute weight.



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

def weight
  @weight
end

Class Method Details

.listObject



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

def list
  all.map(&:path)
end

.sampleObject



18
19
20
21
22
23
# File 'lib/moodwall/wallpaper.rb', line 18

def sample
  record = within_current_mood.shuffle.sort.first
  raise(WallpaperNotFoundError, "Can't find wallpaper.") if record.nil?
  record.increment_weight!
  record
end

.within_current_moodObject



25
26
27
28
# File 'lib/moodwall/wallpaper.rb', line 25

def within_current_mood
  mood = Moodwall::Mood.current
  mood.nil? ? all : all.select { |w| w.mood_id == mood.id }
end

Instance Method Details

#<=>(other) ⇒ Object



40
41
42
43
44
45
46
47
# File 'lib/moodwall/wallpaper.rb', line 40

def <=>(other)
  other_weight = other.weight
  if other_weight != weight
    -(other_weight <=> weight)
  else
    [-1, 0, 1].sample
  end
end

#increment_weight!Object



49
50
51
52
# File 'lib/moodwall/wallpaper.rb', line 49

def increment_weight!
  @weight += 1
  save
end

#saveObject



35
36
37
38
# File 'lib/moodwall/wallpaper.rb', line 35

def save
  check_file
  super
end