class Pagy::Calendar
Base class for time units subclasses (Year, Quarter, Month, Week, Day)
:nodoc:
def active_period
def active_period [[@starting, @from].max, [@to - 1, @ending].min] # -1 sec: include only last unit day end
def create(unit, vars)
def create(unit, vars) raise InternalError, "unit must be in #{UNITS.inspect}; got #{unit}" unless UNITS.include?(unit) name = unit.to_s name[0] = name[0].capitalize Object.const_get("Pagy::Calendar::#{name}").new(vars) end
def initialize(vars) # rubocop:disable Lint/MissingSuper
Merge and validate the options, do some simple arithmetic and set a few instance variables
def initialize(vars) # rubocop:disable Lint/MissingSuper raise InternalError, 'Pagy::Calendar is a base class; use one of its subclasses' if instance_of?(Pagy::Calendar) vars = self.class::DEFAULT.merge(vars) # subclass specific default normalize_vars(vars) # general default setup_vars(page: 1) setup_unit_vars setup_params_var raise OverflowError.new(self, :page, "in 1..#{@last}", @page) if @page > @last @prev = (@page - 1 unless @page == 1) @next = @page == @last ? (1 if @vars[:cycle]) : @page + 1 end
def label(opts = {})
def label(opts = {}) label_for(@page, opts) end
def label_for(page, opts = {})
def label_for(page, opts = {}) opts[:format] ||= @vars[:format] localize(starting_time_for(page.to_i), opts) # page could be a string end
def localize(time, opts)
def localize(time, opts) time.strftime(opts[:format]) end
def offset_units_for(page)
Number of units to offset from the @initial time, in order to get the ordered starting time for the page.
def offset_units_for(page) @order == :asc ? page - 1 : @pages - page end
def setup_unit_vars
def setup_unit_vars raise VariableError.new(self, :format, 'to be a strftime format', @vars[:format]) unless @vars[:format].is_a?(String) raise VariableError.new(self, :order, 'to be in [:asc, :desc]', @order) \ unless %i[asc desc].include?(@order = @vars[:order]) @starting, @ending = @vars[:period] raise VariableError.new(self, :period, 'to be a an Array of min and max local Time instances', @vars[:period]) \ unless @starting.is_a?(Time) && @ending.is_a?(Time) && !@starting.utc? && !@ending.utc? && @starting <= @ending @with_zone = @starting.is_a?(ActiveSupport::TimeWithZone) # remove in 6.0 and reu]place Time in the line above end