Skip to content

Commit

Permalink
Fix bug when enum value is nil
Browse files Browse the repository at this point in the history
  • Loading branch information
westonganger committed Nov 12, 2024
1 parent 17192d5 commit e9d8b02
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 12 deletions.
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ CHANGELOG

- **Unreleased**
* [View Diff](https://github.com/westonganger/active_snapshot/compare/v0.5.0...master)
* Nothing yet
* [#63](https://github.com/westonganger/active_snapshot/pull/63) - Fix bug when enum value is nil

- **v0.5.0** - Nov 8, 2024
* [View Diff](https://github.com/westonganger/active_snapshot/compare/v0.4.0...v0.5.0)
Expand Down
13 changes: 7 additions & 6 deletions lib/active_snapshot/models/snapshot.rb
Original file line number Diff line number Diff line change
Expand Up @@ -46,15 +46,16 @@ def metadata=(h)
end

def build_snapshot_item(instance, child_group_name: nil)
attributes = instance.attributes
attributes.each do |k, v|
if instance.class.defined_enums.key?(k)
attributes[k] = instance.class.defined_enums.fetch(k).fetch(v)
end
attrs = instance.attributes

instance.class.defined_enums.each do |enum_col_name, hash|
val = attrs.fetch(enum_col_name)
next if val.nil?
attrs[enum_col_name] = hash.fetch(val)
end

self.snapshot_items.new({
object: attributes,
object: attrs,
item_id: instance.id,
item_type: instance.class.name,
child_group_name: child_group_name,
Expand Down
33 changes: 28 additions & 5 deletions test/models/snapshot_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -88,14 +88,37 @@ def test_build_snapshot_item
@snapshot.build_snapshot_item(Post.first, child_group_name: :foobar)
end

def test_build_snapshot_item_stores_enum_database_value
@snapshot = @snapshot_klass.first
def test_snapshot_item_stores_enum_column_database_value
post = Post.first

snapshot_item = @snapshot.build_snapshot_item(Post.first)
enum_mapping = post.class.defined_enums.fetch("status")

post.status = "published"

snapshot = post.create_snapshot!(identifier: "enum-test")

snapshot_item = snapshot.snapshot_items.find_by(item_type: "Post")

stored_value = snapshot_item.object["status"]

assert_equal 1, stored_value
assert_equal "published", enum_mapping.invert.fetch(stored_value)
end

def test_snapshot_item_handles_nil_enum_column_value
post = Post.first

enum_mapping = post.class.defined_enums.fetch("status")

post.status = nil

snapshot = post.create_snapshot!(identifier: "enum-test")

snapshot_item = snapshot.snapshot_items.find_by(item_type: "Post")

assert snapshot_item.object['status'] == 0
stored_value = snapshot_item.object["status"]

assert_equal @snapshot.snapshot_items.first.object['status'], snapshot_item.object['status']
assert_equal nil, stored_value
end

def test_restore
Expand Down

0 comments on commit e9d8b02

Please sign in to comment.