123456789_123456789_123456789_123456789_123456789_

Module: TZInfo::WithOffset

Relationships & Source Files
Extension / Inclusion / Inheritance Descendants
Included In:
Defined in: lib/tzinfo/with_offset.rb

Overview

The WithOffset module is included in TimeWithOffset, DateTimeWithOffset and TimestampWithOffset. It provides an override for the #strftime method that handles expanding the %Z directive according to the abbreviation of the TimezoneOffset associated with a local time.

Instance Method Summary

Instance Method Details

#if_timezone_offset(result = nil) {|period, result| ... } ⇒ Object (protected)

This method is for internal use only.

Performs a calculation if there is an associated TimezoneOffset.

Parameters:

  • result (Object) (defaults to: nil)

    a result value that can be manipulated by the block if there is an associated TimezoneOffset.

Yields:

  • (period, result)

    if there is an associated TimezoneOffset, the block is yielded to in order to calculate the method result.

Yield Parameters:

Yield Returns:

  • (Object)

    the result of the calculation performed if there is an associated TimezoneOffset.

Returns:

  • (Object)

    the result of the block if there is an associated TimezoneOffset, otherwise the result parameter.

[ GitHub ]

  
# File 'lib/tzinfo/with_offset.rb', line 56

def if_timezone_offset(result = nil) #:nodoc:
  to = timezone_offset
  to ? yield(to, result) : result
end

#strftime(format) ⇒ String

Overrides the Time, DateTime or Timestamp version of strftime, replacing %Z with the abbreviation of the associated TimezoneOffset. If there is no associated offset, %Z is expanded by the base class instead.

All the format directives handled by the base class are supported.

Parameters:

  • format (String)

    the format string.

Returns:

  • (String)

    the formatted time.

Raises:

  • (ArgumentError)

    if format is nil.

[ GitHub ]

  
# File 'lib/tzinfo/with_offset.rb', line 21

def strftime(format)
  raise ArgumentError, 'format must be specified' unless format

  if_timezone_offset do |o|
    abbreviation = nil

    format = format.gsub(/%(%*)Z/) do
      if $1.length.odd?
        # Return %%Z so the real strftime treats it as a literal %Z too.
        "#$1%Z"
      else
        "#$1#{abbreviation ||= o.abbreviation.gsub(/%/, '%%')}"
      end
    end
  end

  super
end