Skip to content

Instantly share code, notes, and snippets.

@mxrguspxrt
Created April 25, 2012 17:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mxrguspxrt/2491558 to your computer and use it in GitHub Desktop.
Save mxrguspxrt/2491558 to your computer and use it in GitHub Desktop.
Timeline for executing blocks in different ranges
# Timeline is a Line that has beginning and the end, it contains many Frames with beginning and end.
module Timeline
# Range has the beginning, end and length.
class Range
attr_accessor :from, :length
attr_reader :to
def initialize from, length
self.from = from
self.length = length
end
def to
from + length
end
end
# Frame has block to be executed.
class Frame < Range
attr_accessor :block
def initialize from, length, &block
super from, length
self.block = block
end
def result
block.call self
end
end
# Line includes fulfils itself with frames and gets their results when #result called.
class Line < Range
attr_accessor :frame_length, :block, :frames
def initialize from, length, frame_length, &block
super from, length
self.frame_length = frame_length
self.block = block
self.frames = []
generate_frames!
end
def generate_frames!
last_frame_to = from
while last_frame_to < to and last_frame_to < (Date.today+1)
frame = Frame.new(last_frame_to, frame_length, &block)
last_frame_to = frame.to
@frames << frame
end
@frames
end
def result
frames.map(&:result)
end
end
end
@mxrguspxrt
Copy link
Author

Timeline::Line.new(from, length, frame_length) do |frame|
puts frame.inspect
end.result

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment