Class: TimeCalc::Op

Inherits:
Object
  • Object
show all
Defined in:
lib/time_calc/op.rb

Overview

Abstraction over chain of time math operations that can be applied to a time or date.

Examples:

op = TimeCalc.+(1, :day).floor(:hour)
# => <TimeCalc::Op +(1 day).floor(hour)>
op.call(Time.now)
# => 2019-07-04 22:00:00 +0300
array_of_time_values.map(&op)
# => array of "next day, floor to hour" for each element

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(chain = []) ⇒ Op

Note:

Prefer ‘TimeCalc.<operation>` (for example TimeCalc#+) to create operations.

Returns a new instance of Op.



19
20
21
# File 'lib/time_calc/op.rb', line 19

def initialize(chain = [])
  @chain = chain
end

Instance Attribute Details

#chainObject (readonly)



15
16
17
# File 'lib/time_calc/op.rb', line 15

def chain
  @chain
end

Instance Method Details

#+(span, unit) ⇒ Op

Adds ‘+(span, unit)` to method chain

Returns:

See Also:



# File 'lib/time_calc/op.rb', line 32

#-(span, unit) ⇒ Op

Adds ‘-(span, unit)` to method chain

Returns:

See Also:



# File 'lib/time_calc/op.rb', line 32

#call(date_or_time) ⇒ Date, ...

Performs the whole chain of operation on parameter, returning the result.

Parameters:

  • date_or_time (Date, Time, DateTime)

Returns:

  • (Date, Time, DateTime)

    Type of the result is always the same as type of the parameter



61
62
63
64
65
# File 'lib/time_calc/op.rb', line 61

def call(date_or_time)
  @chain.reduce(Value.new(date_or_time)) { |val, (name, args, block)|
    val.public_send(name, *args, &block)
  }.unwrap
end

#ceil(unit) ⇒ Op

Adds ‘ceil(span, unit)` to method chain

Returns:

See Also:



# File 'lib/time_calc/op.rb', line 32

#floor(unit) ⇒ Op

Adds ‘floor(span, unit)` to method chain

Returns:

See Also:



# File 'lib/time_calc/op.rb', line 32

#inspectObject



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

def inspect
  '<%s %s>' % [self.class, @chain.map { |name, args, _| "#{name}(#{args.join(' ')})" }.join('.')]
end

#iterate(span, unit, &block) ⇒ Op

Adds ‘iterate(span, unit, &block)` to method chain

Returns:

See Also:



# File 'lib/time_calc/op.rb', line 32

#round(unit) ⇒ Op

Adds ‘round(span, unit)` to method chain

Returns:

See Also:



# File 'lib/time_calc/op.rb', line 32

#to_procProc

Allows to pass operation with ‘&operation`.

Returns:

  • (Proc)


70
71
72
# File 'lib/time_calc/op.rb', line 70

def to_proc
  method(:call).to_proc
end