From e97f2f14777823659b553b28266170eb25a2f57c Mon Sep 17 00:00:00 2001 From: "Daniel (dB.) Doubrovkine" Date: Sun, 18 Oct 2026 11:00:10 -0400 Subject: [PATCH] Encode file bytes in Base64 and data URIs Finish #45 with persisted multi-chunk binary regression coverage. Co-authored-by: Yudho Ahmad Diponegoro Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- CHANGELOG.md | 1 + lib/mongoid/grid_fs.rb | 2 +- test/grid_fs_interfaces_test.rb | 10 ++++++++++ test/mongoid-grid_fs_test.rb | 2 +- 4 files changed, 13 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 13fa065..1e57c41 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,6 @@ ### 2.6.1 (Next) +* [#45](https://github.com/mongoid/mongoid-grid_fs/pull/45): Encode stored file bytes rather than the model description in Base64 and data URIs - [@yudho](https://github.com/yudho), [@dblock](https://github.com/dblock). * [#86](https://github.com/mongoid/mongoid-grid_fs/pull/86): Expand persisted GridFS coverage for streaming, upload failures, namespaces, attributes, queries, historical records without `updateDate`, and Rails responses - [@dblock](https://github.com/dblock). * [#85](https://github.com/mongoid/mongoid-grid_fs/pull/85): Report test coverage to Coveralls and update CI badges - [@dblock](https://github.com/dblock). * [#84](https://github.com/mongoid/mongoid-grid_fs/pull/84): Migrate Danger to danger-pr-comment workflows - [@dblock](https://github.com/dblock). diff --git a/lib/mongoid/grid_fs.rb b/lib/mongoid/grid_fs.rb index 289bffb..63ed8f3 100644 --- a/lib/mongoid/grid_fs.rb +++ b/lib/mongoid/grid_fs.rb @@ -353,7 +353,7 @@ def data end def base64 - Array(to_s).pack('m') + Array(data).pack('m') end def data_uri(_options = {}) diff --git a/test/grid_fs_interfaces_test.rb b/test/grid_fs_interfaces_test.rb index 2825903..fca1a64 100644 --- a/test/grid_fs_interfaces_test.rb +++ b/test/grid_fs_interfaces_test.rb @@ -97,6 +97,16 @@ def test_normalized_upload_attributes_survive_reload assert_equal "binary\x00payload".b, file.data end + def test_base64_and_data_uri_encode_the_stored_bytes + payload = "binary\x00\xffpayload".b * 12 + file = @namespace.put(StringIO.new(payload), filename: 'encoded.bin', chunk_size: 8) + file = @namespace.get(file.id) + + assert_equal [payload].pack('m'), file.base64 + assert_equal payload, file.base64.unpack1('m') + assert_equal "data:application/octet-stream;base64,#{[payload].pack('m').chomp}", file.data_uri + end + def test_explicit_gridfs_attributes uploaded_at = Time.utc(2021, 2, 3) file = @namespace.put( diff --git a/test/mongoid-grid_fs_test.rb b/test/mongoid-grid_fs_test.rb index 43ca9b9..b6613e5 100644 --- a/test/mongoid-grid_fs_test.rb +++ b/test/mongoid-grid_fs_test.rb @@ -103,7 +103,7 @@ g = assert { GridFs.get(id) } content_type = g.content_type - base64 = [g.to_s].pack('m').chomp + base64 = [g.data].pack('m').chomp data_uri = "data:#{content_type};base64,".concat(base64)