Skip to content

Commit

Permalink
Merge pull request #169 from bekicot/rails-fix
Browse files Browse the repository at this point in the history
Fix errors when loading array of datetime
  • Loading branch information
haffla authored Oct 15, 2023
2 parents 2441d85 + 3e16159 commit f1c2db8
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 5 deletions.
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

0 comments on commit f1c2db8

Please sign in to comment.