Sha256: 9cc1d0a877831ec1f8ee9c1380453abb58ac19458f3fa2c7c206d9e89462293e

Contents?: true

Size: 1.66 KB

Versions: 1

Compression:

Stored size: 1.66 KB

Contents

# frozen_string_literal: true

module Katalyst
  module Tables
    module Body
      # Formats the value as a date
      # @param format [String] date format, defaults to :table
      # @param relative [Boolean] if true, the date may be(if within 5 days) shown as a relative date
      class DateComponent < BodyCellComponent
        def initialize(table, record, attribute, format: :table, relative: true, **options)
          super(table, record, attribute, **options)

          @format   = format
          @relative = relative
        end

        def value
          super&.to_date
        end

        def rendered_value
          @relative ? relative_time : absolute_time
        end

        private

        def absolute_time
          value.present? ? I18n.l(value, format: @format) : ""
        end

        def relative_time
          if value.blank?
            ""
          else
            days_ago_in_words(value)&.capitalize || absolute_time
          end
        end

        def default_html_attributes
          @relative && value.present? && days_ago_in_words(value).present? ? { title: absolute_time } : {}
        end

        def days_ago_in_words(value)
          from_time        = value.to_time
          to_time          = Date.current.to_time
          distance_in_days = ((to_time - from_time) / (24.0 * 60.0 * 60.0)).round

          case distance_in_days
          when 0
            "today"
          when 1
            "yesterday"
          when -1
            "tomorrow"
          when 2..5
            "#{distance_in_days} days ago"
          when -5..-2
            "#{distance_in_days.abs} days from now"
          end
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
katalyst-tables-3.0.0.beta1 app/components/katalyst/tables/body/date_component.rb