Skip to content

Commit

Permalink
Merge pull request #5190 from rubyforgood/local-time
Browse files Browse the repository at this point in the history
Render Local Time
  • Loading branch information
FireLemons authored Sep 23, 2023
2 parents 51f54da + ce0c866 commit 470c61c
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 0 deletions.
1 change: 1 addition & 0 deletions app/components/local_time_component.html.erb
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<div><%= local_time %></div>
34 changes: 34 additions & 0 deletions app/components/local_time_component.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# frozen_string_literal: true

class LocalTimeComponent < ViewComponent::Base
include ActionController::Cookies
attr_reader :format, :unix_timestamp

def initialize(format:, unix_timestamp:)
@format = format
@unix_timestamp = unix_timestamp
end

def local_time
# Time format should be passed as 12 or 24 only
unless [12, 24].include?(format)
raise ArgumentError, "Invalid time format argument"
end

time = Time.at(unix_timestamp).in_time_zone(@time_zone)
time_format = format == 12 ? "%I:%M %p" : "%H:%M"
formatted_date = time.strftime("%B %d, %Y")
time_of_day = time.strftime(time_format)
time_zone = time.zone
formatted_date + " at " + time_of_day + " " + time_zone
end

private

def before_render
browser_tz = ActiveSupport::TimeZone.find_tzinfo(cookies[:browser_time_zone])
ActiveSupport::TimeZone.all.find { |zone| zone.tzinfo == browser_tz } || Time.zone
rescue TZInfo::UnknownTimezone, TZInfo::InvalidTimezoneIdentifier
@time_zone = Time.zone
end
end
17 changes: 17 additions & 0 deletions spec/components/local_time_component_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# frozen_string_literal: true

require "rails_helper"

RSpec.describe LocalTimeComponent, type: :component do
it "render correct date from user local time" do
component = described_class.new(format: 12, unix_timestamp: 1693825843)
render_inline(component)
expect(page).to have_text("September 04, 2023")
end

it "does not render correct date from user local time" do
component = described_class.new(format: 12, unix_timestamp: 1693825843)
render_inline(component)
expect(page).to_not have_text("September 06, 2023")
end
end

0 comments on commit 470c61c

Please sign in to comment.