Skip to content

Instantly share code, notes, and snippets.

@adamwiggall
Created August 22, 2016 16:58
Show Gist options
  • Save adamwiggall/9ba12839980c03bfc7ab4a2beb7e79be to your computer and use it in GitHub Desktop.
Save adamwiggall/9ba12839980c03bfc7ab4a2beb7e79be to your computer and use it in GitHub Desktop.
class DateRange
attr_accessor :range, :format, :custom_start_date, :custom_end_date
def initialize(range, options = {})
@range = range ? range.to_s : options[:default].to_s
@format = options[:format]
@custom_start_date = options[:start_date].to_formatted_date(@format) if options[:start_date]
@custom_end_date = options[:end_date].to_formatted_date(@format) if options[:end_date]
end
def to_a
[start_date, end_date]
end
def to_r
start_date..end_date
end
def cover? d
to_r.cover? d
end
def self.from_params params, format = nil
new params[:range] || params[:date_range],
start_date: params[:start_date],
end_date: params[:end_date],
format: format
end
def to_params merge_with = {}
if @range == "your_dates"
h = {range: :your_dates, start_date: start_date, end_date: end_date}
else
h = {range: @range}
end
merge_with.merge h
end
def blank?
@range.blank?
end
def all?
@range == 'all_dates'
end
def start_date=(other)
@custom_start_date = other
end
def end_date=(other)
@custom_end_date = other
end
def start_date_s
self.start_date.is_a?(Date) ? self.start_date.to_s(:db) : self.start_date
end
def end_date_s
self.end_date.is_a?(Date) ? self.end_date.to_s(:db) : self.end_date
end
def start_date
case @range
when '30_days'
Date.today - 30
when '60_days'
Date.today - 60
when '90_days'
Date.today - 90
when '120_days'
Date.today - 120
when 'last_year'
Date.today.advance(:years => -1).beginning_of_year
when 'last_quarter'
(Date.today.beginning_of_quarter - 1.day).beginning_of_quarter
when 'last_month'
Date.today.last_month.beginning_of_month
when 'this_year', 'ytd'
Date.today.beginning_of_year
when 'this_quarter'
Date.today.beginning_of_quarter
when 'this_month'
Date.today.beginning_of_month
when 'your_dates'
@custom_start_date
when 'all_dates'
100.years.ago.to_date.beginning_of_year
else
Date.today.beginning_of_month
end
end
def start
start_date
end
def end_date
case @range
when 'last_month'
Date.today.beginning_of_month - 1.day
when 'last_year'
Date.today.beginning_of_month.beginning_of_year - 1.day
when 'last_quarter'
Date.today.beginning_of_quarter - 1.day
when "this_month"
Date.today.end_of_month
when "this_year"
Date.today.end_of_year
when "this_quarter"
Date.today.end_of_quarter
when 'ytd'
Date.today + 1
when 'your_dates'
@custom_end_date
else
Date.today + 1
end
end
def end
end_date
end
private
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment