Skip to content

Commit 44eff6a

Browse files
committed
fix(collection): add to_json and to_yaml for RethinkORM::Collection
1 parent f7bb3ba commit 44eff6a

File tree

4 files changed

+44
-9
lines changed

4 files changed

+44
-9
lines changed

spec/associations_spec.cr

+7-8
Original file line numberDiff line numberDiff line change
@@ -80,14 +80,13 @@ describe RethinkORM::Associations do
8080
car = Car.create!(brand: "Toyota")
8181
car.persisted?.should be_true
8282

83-
wheels = [] of Wheel
84-
4.times do |v|
85-
wheel = Wheel.new(width: 10 + v)
86-
wheel.car = car
87-
wheel = wheel.save!
88-
wheel.persisted?.should be_true
89-
car.id.should eq wheel.car_id
90-
wheels << wheel
83+
wheels = Array.new(4) do |v|
84+
Wheel.new(width: 10 + v).tap do |wheel|
85+
wheel.car = car
86+
wheel = wheel.save!
87+
wheel.persisted?.should be_true
88+
car.id.should eq wheel.car_id
89+
end
9190
end
9291

9392
# Check the associations can be retrieved

spec/collection_spec.cr

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
require "./spec_helper"
2+
3+
module RethinkORM
4+
describe Collection do
5+
it "#to_json" do
6+
car = Car.create!(brand: "Toyota")
7+
car.persisted?.should be_true
8+
9+
wheel_ids = Array.new(4) do |v|
10+
Wheel.new(width: 10 + v).tap do |wheel|
11+
wheel.car = car
12+
wheel = wheel.save!
13+
wheel.persisted?.should be_true
14+
car.id.should eq wheel.car_id
15+
end.id.as(String)
16+
end.sort
17+
18+
Array(Wheel)
19+
.from_json(car.wheels.to_json)
20+
.compact_map(&.id).sort!
21+
.should eq(wheel_ids)
22+
end
23+
end
24+
end

src/rethinkdb-orm/utils/association_collection.cr

+1-1
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ class RethinkORM::AssociationCollection(Owner, Target)
88

99
delegate :find, :find!, to: Target
1010

11-
delegate :each, to: :all
11+
delegate :each, :to_yaml, :to_json, to: :all
1212

1313
def initialize(@owner, foreign_key = nil)
1414
@foreign_key = !foreign_key ? "#{Owner.table_name}_id" : foreign_key.to_s

src/rethinkdb-orm/utils/collection.cr

+12
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,18 @@ module RethinkORM
5050
end
5151
end
5252

53+
def to_json(json : JSON::Builder) : Nil
54+
json.array do
55+
each(&.to_json(json))
56+
end
57+
end
58+
59+
def to_yaml(yaml : YAML::Nodes::Builder) : Nil
60+
yaml.sequence(reference: self) do
61+
each(&.to_yaml(yaml))
62+
end
63+
end
64+
5365
def stop
5466
@iterator.stop
5567
super

0 commit comments

Comments
 (0)