Skip to content

Commit

Permalink
16222 - Add fetch function for request object in agents
Browse files Browse the repository at this point in the history
This commit adds a fetch method to both the request and result objects
that will help users create more deterministic code in the face of
missing data
  • Loading branch information
ripienaar committed Sep 4, 2012
1 parent c9ef3db commit 7f2cbfd
Show file tree
Hide file tree
Showing 6 changed files with 33 additions and 0 deletions.
4 changes: 4 additions & 0 deletions lib/mcollective/rpc/reply.rb
Expand Up @@ -69,6 +69,10 @@ def [](key)
@data[key]
end

def fetch(key, default)
@data.fetch(key, default)
end

# Returns a compliant Hash of the reply that should be sent
# over the middleware
def to_hash
Expand Down
5 changes: 5 additions & 0 deletions lib/mcollective/rpc/request.rb
Expand Up @@ -36,6 +36,11 @@ def [](key)
return @data[key]
end

def fetch(key, default)
return nil unless @data.is_a?(Hash)
return @data.fetch(key, default)
end

def to_hash
return {:agent => @agent,
:action => @action,
Expand Down
4 changes: 4 additions & 0 deletions lib/mcollective/rpc/result.rb
Expand Up @@ -24,6 +24,10 @@ def []=(idx, item)
@results[idx] = item
end

def fetch(key, default)
@results.fetch(key, default)
end

def each
@results.each_pair {|k,v| yield(k,v) }
end
Expand Down
12 changes: 12 additions & 0 deletions spec/unit/rpc/request_spec.rb
Expand Up @@ -100,6 +100,18 @@ module RPC
end
end

describe "#fetch" do
it "should return nil for non hash data" do
@req[:body][:data] = "foo"
Request.new(@req, @ddl)["foo"].should == nil
end

it "should fetch data with the correct default behavior" do
@request.fetch(:foo, "default").should == "bar"
@request.fetch(:rspec, "default").should == "default"
end
end

describe "#to_hash" do
it "should have the correct keys" do
@request.to_hash.keys.sort.should == [:action, :agent, :data]
Expand Down
7 changes: 7 additions & 0 deletions spec/unit/rpc/result_spec.rb
Expand Up @@ -44,6 +44,13 @@ module RPC
end
end

describe "#fetch" do
it "should fetch data with the correct default behavior" do
@result.fetch(:foo, "default").should == "bar"
@result.fetch(:rspec, "default").should == "default"
end
end

describe "#each" do
it "should itterate all the pairs" do
data = {}
Expand Down
1 change: 1 addition & 0 deletions website/changelog.md
Expand Up @@ -8,6 +8,7 @@ toc: false

|Date|Description|Ticket|
|----|-----------|------|
|2012/09/04|Add a fetch method that mimic Hash#fetch to RPC Results and Requests|16222|
|2012/09/04|Include the required mcollective version in packages that include the requirement|16173|
|2012/08/29|Add a RabbitMQ specific connector plugin|16168|
|2012/08/22|DDL files can now specify which is the minimal version of mcollective they require|15850|
Expand Down

0 comments on commit 7f2cbfd

Please sign in to comment.