Skip to content

Commit

Permalink
Fix JSON-encoding ActiveStorage::Filename
Browse files Browse the repository at this point in the history
ActiveStorage::Filename was missing quotes when encoded,
generating invalid json like this -

```
JSON.generate(foo: ActiveStorage::Filename.new("bar.pdf") # => '{"foo":bar.pdf}'
```

Delete to_json and rely on the implementation from ActiveSupport::ToJsonWithActiveSupportEncoder
  • Loading branch information
jdelStrother committed Feb 6, 2024
1 parent 6b2a9f1 commit 54d3934
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 4 deletions.
4 changes: 4 additions & 0 deletions activestorage/CHANGELOG.md
@@ -1,3 +1,7 @@
* Fix JSON-encoding of `ActiveStorage::Filename` instances.

*Jonathan del Strother*

* Fix N+1 query when fetching preview images for non-image assets

*Aaron Patterson & Justin Searls*
Expand Down
4 changes: 0 additions & 4 deletions activestorage/app/models/active_storage/filename.rb
Expand Up @@ -69,10 +69,6 @@ def as_json(*)
to_s
end

def to_json
to_s
end

def <=>(other)
to_s.downcase <=> other.to_s.downcase
end
Expand Down
6 changes: 6 additions & 0 deletions activestorage/test/models/filename_test.rb
Expand Up @@ -53,4 +53,10 @@ class ActiveStorage::FilenameTest < ActiveSupport::TestCase
test "compare sanitized" do
assert_operator ActiveStorage::Filename.new("foo-bar.pdf"), :==, ActiveStorage::Filename.new("foo\tbar.pdf")
end

test "encoding to json" do
assert_equal '"foo.pdf"', ActiveStorage::Filename.new("foo.pdf").to_json
assert_equal '{"filename":"foo.pdf"}', { filename: ActiveStorage::Filename.new("foo.pdf") }.to_json
assert_equal '{"filename":"foo.pdf"}', JSON.generate(filename: ActiveStorage::Filename.new("foo.pdf"))
end
end

0 comments on commit 54d3934

Please sign in to comment.