Module: Tins::TimeDummy

Defined in:
lib/tins/time_dummy.rb

Class Method Summary collapse

Class Method Details

.included(modul) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/tins/time_dummy.rb', line 6

def self.included(modul)
  class << modul
    alias really_new new
    alias really_now now

    remove_method :now rescue nil
    remove_method :new rescue nil

    def dummy=(value)
      if value.respond_to?(:to_str)
        value = Time.parse(value.to_str)
      elsif value.respond_to?(:to_time)
        value = value.to_time
      end
      @dummy = value
    end

    def dummy(value = nil)
      if value.nil?
        if defined?(@dummy)
          @dummy
        end
      else
        begin
          old_dummy = @dummy
          self.dummy = value
          yield
        ensure
          self.dummy = old_dummy
        end
      end
    end

    if Tins::StringVersion.compare(RUBY_VERSION, :>=, "3.0")
      def new(*a, **kw)
        if dummy
          dummy.dup
        elsif caller.first =~ /`now`/
          really_now(**kw)
        else
          really_new(*a, **kw)
        end
      end
    else
      def new(*a)
        if dummy
          dummy.dup
        elsif caller.first =~ /`now`/
          really_now
        else
          really_new(*a)
        end
      end
    end

    def now
      new
    end
  end
  super
end