Module: StringToNewDate

Included in:
String
Defined in:
lib/ruby-rails-extensions/extensions/to_new_date.rb

Constant Summary collapse

NEW_DATE_REGEXES =
{
  # MM DD YYYY
  mm_dd_yyyy: /\A\d{2}\D?\d{2}\D?\d{4}\z/,
  # YYYY MM DD
  yyyy_mm_dd: /\A\d{4}\D?\d{2}\D?\d{2}\z/,
  # MM DD YY
  mm_dd_yy: /\A\d{2}\D?\d{2}\D?\d{2}\z/,
  # (M)M (D)D (YY)YY
  m_d_yy: %r{\A(\d{1,2})[-|/](\d{1,2})[-|/](\d+)\z},
  # M(M) YY(YY)
  m_yy: %r{\A(\d{1,2})[-/](\d{2,4})\z}
}.freeze

Instance Method Summary collapse

Instance Method Details

#to_new_date(options = {}) ⇒ Date, ...

Converts a string to a date object when following one of the following patterns (no space delimiters):

- MM-DD-YYYY
- YYYY-MM-DD
- MM-DD-YY
- (M)M-(D)D-(YY)YY => "()" optional values

Parameters:

  • options (Hash) (defaults to: {})

Options Hash (options):

  • :return_orig (Boolean)

    If true, the non-converted string will be returned instead of nil. Default is to return nil when conversion fails.

  • :quarter (String)

    If date extraction successful, the date will be converted to the beginning or ending of the quarter. Accepts: ‘begin(ning)’ and ‘end(ing)’

Returns:



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/ruby-rails-extensions/extensions/to_new_date.rb', line 39

def to_new_date(options = {})
  opts = {
    return_orig: false,
    quarter: nil
  }.merge(options || {})

  new_date = extract_date

  if new_date.nil?
    return opts[:return_orig] ? self : nil
  end

  if opts[:quarter].to_s.match?(/begin/i)
    return new_date.beginning_of_quarter
  end

  if opts[:quarter].to_s.match?(/end/i)
    return new_date.end_of_quarter
  end

  new_date
end

#to_new_date_mm_yyDate?

Converts a string to a date object. The only pattern accepted: ‘MM YY’

Returns:

See Also:



76
77
78
79
80
# File 'lib/ruby-rails-extensions/extensions/to_new_date.rb', line 76

def to_new_date_mm_yy
  return unless NEW_DATE_REGEXES[:m_yy].match?(self)

  m_yy_date
end

#to_new_date_safeObject

Recovers from any error when calling #to_new_date



63
64
65
66
67
# File 'lib/ruby-rails-extensions/extensions/to_new_date.rb', line 63

def to_new_date_safe(...)
  to_new_date(...)
rescue
  nil
end