Module: OpenHAB::CoreExt::Ruby::Range

Included in:
Range
Defined in:
lib/openhab/core_ext/ruby/range.rb

Overview

Extensions to Range

Instance Method Summary collapse

Instance Method Details

#circular?true, false

Checks if this range is circular

A circular range is one whose data type will repeat if keep you keep calling #succ on it, and whose beginning is after its end.

Used by #cover? to check if the value is between end and begin, instead of begin and end.

Returns:

  • (true, false)


54
55
56
57
58
59
60
61
62
63
64
# File 'lib/openhab/core_ext/ruby/range.rb', line 54

def circular?
  return false if self.begin.nil? || self.end.nil?
  return false if self.begin <= self.end

  case self.begin || self.end
  when java.time.LocalTime, java.time.MonthDay, java.time.Month
    true
  else
    false
  end
end

#cover?(object) ⇒ Boolean

Returns:

  • (Boolean)


8
9
10
11
12
13
14
15
16
# File 'lib/openhab/core_ext/ruby/range.rb', line 8

def cover?(object)
  # inverted circular range
  if circular?
    return object >= self.begin || object < self.end if exclude_end?

    return object >= self.begin || object <= self.end
  end
  super
end

#eachObject

normal Range#each will not yield at all if begin > end



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/openhab/core_ext/ruby/range.rb', line 27

def each
  return super unless circular?
  return to_enum(:each) unless block_given?

  val = self.begin
  loop do
    is_end = val == self.end
    break if is_end && exclude_end?

    yield val
    break if is_end

    val = val.succ
  end
end