Module: Tins::DateDummy

Defined in:
lib/tins/date_dummy.rb

Overview

A module that provides dummy date functionality for testing purposes.

Examples:

Setting a dummy date

Date.dummy = Date.parse('2009-09-09')

Using a dummy date in a block

Date.dummy Date.parse('2009-09-09') do
  # Your code here
end

Class Method Summary collapse

Class Method Details

.included(modul) ⇒ Object

The included method is a hook that gets called when this module is included in another class or module.

It sets up date freezing functionality by extending the including class/module with special date handling methods. The method modifies the including class/module’s singleton class to provide dummy date capabilities.

Parameters:

  • modul (Object)

    the class or module that includes this module



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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/tins/date_dummy.rb', line 23

def self.included(modul)
  class << modul
    alias really_today today

    remove_method :today rescue nil

    # Sets the dummy date value for date freezing functionality.
    #
    # @param value [Date, String] the date value to set as dummy
    def dummy=(value)
      if value.respond_to?(:to_str)
        value = Date.parse(value.to_str)
      elsif value.respond_to?(:to_date)
        value = value.to_date
      end
      @dummy = value
    end

    # The dummy method provides a way to set and temporarily override a
    # dummy value within a block.
    #
    # @param value [Object] the dummy value to set, or nil to get the
    # current dummy value
    # @yield [] yields control to the block if a value is provided
    # @return [Object] the current dummy value if no value parameter was
    # provided
    # @yieldparam value [Object] the dummy value to set within the block
    # @yieldreturn [Object] the result of the block execution
    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

    # The today method returns the current date. When a dummy date is set,
    # it returns a duplicate of that date. Otherwise, it delegates to the
    # actual today method implementation.
    #
    # @return [Date] the current date or the dummy date if set
    def today
      if dummy
        dummy.dup
      elsif caller.first =~ /`today`/
        really_today
      else
        really_today
      end
    end
  end
  super
end