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



57
58
59
60
61
# File 'lib/time_calc/op.rb', line 57

def call(date_or_time)
  @chain.reduce(Value.new(date_or_time)) { |val, (name, *args)|
    val.public_send(name, *args)
  }.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

#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)


66
67
68
# File 'lib/time_calc/op.rb', line 66

def to_proc
  method(:call).to_proc
end