knaveofdiamonds (owner)

Forks

Revisions

gist: 203385 Download_button fork
public
Public Clone URL: git://gist.github.com/203385.git
Embed All Files: show embed
schedule class #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# Create a schedule for a network
# called by Service#schedule
# ie radio4.schedule.today or radio4.schedule.this_week
 
# Is this not more of a ScheduleBuilder rather than the actual schedule - it feels a little like
# the arrays this generates are the "schedule" objects?
class Schedule
  
  def initialize(service)
    @service = service
  end
  
  # Would it be legal to call this method before calling today? I.e. before a call to today
  # this would return nil, after it would return [[], [], ...] which seems inconsistent. Do
  # you need it at all in fact?
  attr_accessor :schedule
    
  def today
    # Is this really expensive so you want to call it lazily? I guess I'm not sure why
    # we do this here rather than in the constructor?
    broadcasts = @service.broadcasts.today
    @schedule = fill(day, broadcasts)
  end
 
  # Added private. A bit hard to tell without knowing the context, but my guess is that
  # these methods don't really need to be in the public interface?
  private
  
  def day
    # Instead of (1..24).map { [] } you can also do - possibly a bit clearer as to the fact
    # you're just creating a new array and avoids creating an extra range object:
    Array.new(24) { [] }
  end
    
  def week
    # Same as for day, above
    Array.new(7) { day }
  end
 
  def fill(schedule, broadcasts)
    broadcasts.each do |broadcast|
      broadcast_hours(broadcast).each do |slot|
        schedule[slot] << broadcast
      end
    end
    schedule
  end
 
  # I found all the ternaries a little overwhelming on first glance through - it took me a
  # while to figure out that you were building up a schedule in the above method, so I've split
  # them out. I'd half be inclined to extract these three methods out into their own little class
  # - BroadcastHourView or somesuch, so they could be tested - they feel slightly out of place
  # in Schedule.
  def broadcast_hours(broadcast)
    (broadcast_start_hour(broadcast)..broadcast_finish_hour(broadcast))
  end
 
  def broadcast_start_hour(broadcast)
    (broadcast.start_time < Date.today.midnight) ? 0 : broadcast.start_time.hour
  end
 
  def broadcast_finish_hour(broadcast)
    last_timeslot = (broadcast.end_time > Date.tomorrow.midnight) ? 23 : (broadcast.end_time.hour - 1)
    last_timeslot += 1 if (broadcast.end_time.min > 0 || broadcast.end_time.sec > 0 )
  end
end