Class: Code::Object::Duration

Inherits:
Code::Object show all
Defined in:
lib/code/object/duration.rb

Instance Attribute Summary

Attributes inherited from Code::Object

#raw

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Code::Object

#<=>, #==, call, #code_and_operator, code_and_operator, #code_different, code_different, code_equal_equal, #code_equal_equal, code_equal_equal_equal, #code_equal_equal_equal, code_exclamation_point, #code_exclamation_point, code_exclusive_range, #code_exclusive_range, #code_inclusive_range, code_inclusive_range, code_new, code_or_operator, #code_or_operator, code_self, #code_self, #code_to_string, code_to_string, falsy?, #falsy?, #hash, inspect, maybe, multi_fetch, #multi_fetch, repeat, #sig, sig, #to_json, to_s, truthy?, #truthy?, |

Constructor Details

#initialize(*args, **_kargs, &_block) ⇒ Duration

Returns a new instance of Duration.



6
7
8
9
10
11
12
13
14
# File 'lib/code/object/duration.rb', line 6

def initialize(*args, **_kargs, &_block)
  raw = args.first || 0.seconds
  raw = raw.raw if raw.is_an?(Object)
  raw = raw.iso8601 if raw.is_an?(::ActiveSupport::Duration)
  @raw = ::ActiveSupport::Duration.parse(raw.to_s)
  super
rescue ::ActiveSupport::Duration::ISO8601Parser::ParsingError
  raise Error, "#{raw.inspect} is not a valid duration"
end

Class Method Details

.nameObject



16
17
18
# File 'lib/code/object/duration.rb', line 16

def self.name
  "Duration"
end

Instance Method Details

#as_jsonObject



51
52
53
# File 'lib/code/object/duration.rb', line 51

def as_json(...)
  raw.as_json(...)
end

#call(**args) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/code/object/duration.rb', line 20

def call(**args)
  operator = args.fetch(:operator, nil)

  case operator.to_s
  when "ago"
    sig(args)
    code_ago
  when "from_now"
    sig(args)
    code_from_now
  else
    super
  end
end

#code_agoObject



35
36
37
# File 'lib/code/object/duration.rb', line 35

def code_ago
  Time.new(raw.ago)
end

#code_from_nowObject



39
40
41
# File 'lib/code/object/duration.rb', line 39

def code_from_now
  Time.new(raw.from_now)
end

#inspectObject



43
44
45
# File 'lib/code/object/duration.rb', line 43

def inspect
  to_s
end

#to_sObject



47
48
49
# File 'lib/code/object/duration.rb', line 47

def to_s
  raw.to_s
end