Skip to content

Commit 8a708f1

Browse files
committed
Merge pull request zendesk#125 from zendesk/sdavidovitz/build
add a Collection#build method
2 parents 4e0f21f + 26929ba commit 8a708f1

File tree

2 files changed

+35
-1
lines changed

2 files changed

+35
-1
lines changed

lib/zendesk_api/collection.rb

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,28 @@ def initialize(client, resource, options = {})
5656
opts = args.last.is_a?(Hash) ? args.pop : {}
5757
opts.merge!(:association => @association)
5858

59-
@resource_class.send(deferrable, @client, @options.merge(opts))
59+
@resource_class.send(deferrable, @client, opts)
60+
end
61+
end
62+
63+
# Convenience method to build a new resource and
64+
# add it to the collection. Fetches the collection as well.
65+
# @param [Hash] options Options or attributes to pass
66+
def build(opts = {})
67+
wrap_resource(opts, true).tap do |res|
68+
self << res
69+
end
70+
end
71+
72+
# Convenience method to build a new resource and
73+
# add it to the collection. Fetches the collection as well.
74+
# @param [Hash] options Options or attributes to pass
75+
def build!(opts = {})
76+
wrap_resource(opts, true).tap do |res|
77+
fetch!
78+
79+
# << does a fetch too
80+
self << res
6081
end
6182
end
6283

@@ -119,6 +140,7 @@ def include(*sideloads)
119140
# @raise [ArgumentError] if the resource doesn't belong in this collection
120141
def <<(item)
121142
fetch
143+
122144
if item.is_a?(Resource)
123145
if item.is_a?(@resource_class)
124146
@resources << item

spec/core/collection_spec.rb

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,18 @@
9898
it "should pass association" do
9999
subject.last.association.should == association
100100
end
101+
102+
it "should #build a resource and add it" do
103+
resource = subject.build
104+
subject.should include(resource)
105+
resource.association.should == subject.association
106+
end
107+
108+
it "should #build! a resource and add it" do
109+
resource = subject.build!
110+
subject.should include(resource)
111+
resource.association.should == subject.association
112+
end
101113
end
102114
end
103115
end

0 commit comments

Comments
 (0)