# frozen_string_literal: true module Ariadne # Converts time into a display-friendly format in a relative time (3d) or absolute date after a default of 30 days class RelativeTimeComponent < Ariadne::Component DEFAULT_TAG = :span TAG_OPTIONS = [DEFAULT_TAG].freeze DEFAULT_DATE_FORMAT = "%b %-d, %Y" DEFAULT_DATE_FORMAT_SWITCH = 30 * 24 * 60 * 60 DEFAULT_CLASSES = "" # @example Default # # <%= render(Ariadne::RelativeTimeComponent.new) { "Example" } %> # # @param tag [Symbol, String] The rendered tag name. # @param classes [String] <%= link_to_classes_docs %> # @param attributes [Hash] <%= link_to_attributes_docs %> def initialize( tag: DEFAULT_TAG, classes: "", time: nil, format: DEFAULT_DATE_FORMAT, date_format_switch: DEFAULT_DATE_FORMAT_SWITCH, force_relative: false, attributes: {} ) raise ArgumentError, "A 'time' argument is required to use the Relative Time component." if time.blank? @now = 1.second.ago @tag = check_incoming_tag(DEFAULT_TAG, tag) @classes = merge_class_names(DEFAULT_CLASSES, classes) @time = time @date_format_switch = date_format_switch @format = format @force_relative = force_relative @attributes = attributes @formatted_date = formatted end private def formatted_time @time.localtime.strftime(@format) end private def time_difference (@now - @time).to_i.abs end private def formatted diff = time_difference if @force_relative || diff < @date_format_switch time_ago_in_words(@time) else @time.localtime.strftime(@format) end end end end