-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Support JSON serialization in Hanami::DB::Struct
We would like structs in Hanami to support simple JSON serialization following the `#to_json` convention. There have been discussions of this functionality in both ROM and Dry-Struct projects, where this was rejected as not appropriate for those gems: - dry-rb/dry-struct#166 - rom-rb/rom#403 This adds a simple `#to_json` method to `Hanami::DB::Struct` to support the simple case for serialization.
- Loading branch information
Showing
2 changed files
with
56 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,48 @@ | ||
# frozen_string_literal: true | ||
|
||
RSpec.describe Hanami::DB::Struct do | ||
let!(:config) do | ||
ROM::Configuration.new(:sql, "sqlite::memory") do |conf| | ||
conf.default.create_table(:users) do | ||
primary_key :id | ||
column :first_name, String | ||
column :last_name, String | ||
end | ||
|
||
conf.relation(:users) do | ||
schema(infer: true) | ||
end | ||
end | ||
end | ||
|
||
let(:rom) { ROM.container(config) } | ||
|
||
before do | ||
module Test | ||
module Entities | ||
class User < Hanami::DB::Struct | ||
def full_name | ||
"#{first_name} #{last_name}" | ||
end | ||
end | ||
end | ||
|
||
class UserRepo < ROM::Repository[:users] | ||
struct_namespace Entities | ||
end | ||
end | ||
end | ||
|
||
describe "#to_json" do | ||
before do | ||
rom.relations[:users].changeset(:create, id: 1, first_name: "L", last_name: "L").commit | ||
end | ||
|
||
it "converts to json" do | ||
repo = Test::UserRepo.new(rom) | ||
struct = repo.users.by_pk(1).one! | ||
expect(struct.full_name).to eq "L L" | ||
expect(struct.to_json).to eq "{\"id\":1,\"first_name\":\"L\",\"last_name\":\"L\"}" | ||
end | ||
end | ||
end |