Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix errors when loading array of datetime #169

Merged
merged 2 commits into from
Oct 15, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion db/config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ default: &default
adapter: postgresql
database: jsonb_accessor
host: <%= ENV.fetch("DATABASE_HOST") { "127.0.0.1" } %>
user: postgres
username: <%= ENV.fetch("DATABASE_USER") { "postgres" } %>

test:
<<: *default
15 changes: 12 additions & 3 deletions lib/jsonb_accessor/helpers.rb
Original file line number Diff line number Diff line change
Expand Up @@ -24,14 +24,23 @@ def deserialize_value(value, attribute_type)
return value if value.blank?

if attribute_type == :datetime
value = if active_record_default_timezone == :utc
Time.find_zone("UTC").parse(value).in_time_zone
value = if value.is_a?(Array)
value.map { |v| parse_date(v) }
else
Time.zone.parse(value)
parse_date(value)
end
end

value
end

# Parse datetime based on the configured default_timezone
def parse_date(datetime)
if active_record_default_timezone == :utc
Time.find_zone("UTC").parse(datetime).in_time_zone
else
Time.zone.parse(datetime)
end
end
end
end
14 changes: 13 additions & 1 deletion spec/jsonb_accessor_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@ def build_class(jsonb_accessor_config, &block)
bar: :integer,
ban: :integer,
baz: [:integer, { array: true }],
bazzle: [:integer, { default: 5 }]
bazzle: [:integer, { default: 5 }],
dates: [:datetime, { array: true }]
) do
enum ban: { foo: 1, bar: 2 }
end
Expand Down Expand Up @@ -58,6 +59,17 @@ def build_class(jsonb_accessor_config, &block)
expect(instance.baz).to eq([1, 2, 3])
end

it "supports array of date" do
# Write
instance.dates = [Date.new(2017, 1, 1), Date.new(2017, 1, 2)]
expect { instance.save! }.to_not raise_error
# Read
instance.reload

expect(instance.dates).to be_kind_of Array
expect(instance.dates.first).to be_kind_of Time
end

it "supports defaults" do
expect(instance.bazzle).to eq(5)
end
Expand Down