diff --git a/lib/hanami/db/struct.rb b/lib/hanami/db/struct.rb index 67dc8ba..d4b6495 100644 --- a/lib/hanami/db/struct.rb +++ b/lib/hanami/db/struct.rb @@ -5,6 +5,14 @@ module DB # @api public # @since 2.2.0 class Struct < ROM::Struct + # @api public + # @since 2.2.0 + # + # Simple conversion of attributes to JSON format, without this method, the instance of the struct gets converted + # to a string + def to_json(*_args) + to_h.to_json + end end end end diff --git a/spec/unit/struct_spec.rb b/spec/unit/struct_spec.rb new file mode 100644 index 0000000..072744b --- /dev/null +++ b/spec/unit/struct_spec.rb @@ -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