Class: Sleep2

Inherits:
Object
  • Object
show all
Includes:
Comparable
Defined in:
lib/sleep2.rb,
lib/sleep2/version.rb

Constant Summary collapse

VERSION =
"0.2.0"

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(duration) ⇒ Sleep2

Returns a new instance of Sleep2.



13
14
15
16
17
18
19
20
21
22
# File 'lib/sleep2.rb', line 13

def initialize duration
  if duration.class.ancestors.include?(Numeric)
    @duration = duration.to_f
  elsif duration.class == self.class
    @duration = duration.duration.to_f
  else
    raise TypeError, "can't convert #{duration.class} into time interval"
  end
  @new = true
end

Instance Attribute Details

#durationObject

Returns the value of attribute duration.



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

def duration
  @duration
end

#new=(value) ⇒ Object (writeonly)

Sets the attribute new

Parameters:

  • value

    the value to set the attribute new to.



11
12
13
# File 'lib/sleep2.rb', line 11

def new=(value)
  @new = value
end

#sleep_procObject

Returns the value of attribute sleep_proc.



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

def sleep_proc
  @sleep_proc
end

Class Method Details

.[](duration) ⇒ Object



6
7
8
# File 'lib/sleep2.rb', line 6

def self.[] duration
  new duration
end

Instance Method Details

#<=>(other) ⇒ Object

Makes sleep instance comparable with another object of its type and integer



51
52
53
54
55
56
57
# File 'lib/sleep2.rb', line 51

def <=>(other)
  if other.kind_of? self.class
    self.duration <=> other.duration
  elsif other.kind_of? Integer
    self.duration <=> other
  end
end

#[](new_duration) ⇒ Object



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

def [] new_duration
  self.duration = new_duration
end

#inspectObject



28
29
30
31
32
33
34
35
36
# File 'lib/sleep2.rb', line 28

def inspect
  # Avoids sleeping the first time it is called (the moment of instantiation)
  unless new?
    self.sleep_proc.call
  else
    self.new   = false
    self.sleep_proc = proc { sleep duration }
  end
end

#new?Boolean

Returns:

  • (Boolean)


24
25
26
# File 'lib/sleep2.rb', line 24

def new?
  @new
end