Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Struct serialize to json #13

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions lib/hanami/db/struct.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
48 changes: 48 additions & 0 deletions spec/unit/struct_spec.rb
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