take strings for body
This makes the assignment for bodies easier when using plain Strings. They get wrapped in an array as per rack definition. For every other type, they have to implement each and get directly set as body or have to be rendered to Strings first.
This commit is contained in:
parent
d10862ce51
commit
ae0b32a58f
|
@ -4,7 +4,8 @@ module Zero
|
|||
#
|
||||
class Response
|
||||
attr_reader :status
|
||||
attr_accessor :header, :body
|
||||
attr_reader :body
|
||||
attr_accessor :header
|
||||
|
||||
# Constructor
|
||||
# Sets default status code to 200.
|
||||
|
@ -24,6 +25,23 @@ module Zero
|
|||
@status = status.to_i
|
||||
end
|
||||
|
||||
# set the body to a new value
|
||||
#
|
||||
# Use this function to set the body to a new value. It can either be an
|
||||
# Object responding to `#each` per rack convention or a kind of string.
|
||||
#
|
||||
# @param content [#each, String] the content of the body
|
||||
def body=(content)
|
||||
content = [content] if content.kind_of?(String)
|
||||
|
||||
unless content.respond_to?(:each) then
|
||||
raise ArgumentError.new(
|
||||
"invalid body! Should be kind of String or respond to #each!")
|
||||
end
|
||||
|
||||
@body = content
|
||||
end
|
||||
|
||||
# Returns the data of the response as an array:
|
||||
# [status, header, body]
|
||||
# to be usable by any webserver.
|
||||
|
|
|
@ -9,4 +9,31 @@ describe Zero::Response do
|
|||
subject.body.should eq([])
|
||||
end
|
||||
end
|
||||
|
||||
describe '#body=' do
|
||||
let(:string) { "new body" }
|
||||
let(:array) { ["new body"] }
|
||||
let(:object_with_each) { {:a => "b" } }
|
||||
let(:invalid_object) { 12345 }
|
||||
|
||||
it "creates an array body for strings" do
|
||||
subject.body = string
|
||||
expect(subject.body).to eq(array)
|
||||
end
|
||||
|
||||
it "sets the body to the array" do
|
||||
subject.body = array
|
||||
expect(subject.body).to be(array)
|
||||
end
|
||||
|
||||
it "sets an object as string when responding to #each" do
|
||||
subject.body = object_with_each
|
||||
expect(subject.body).to be(object_with_each)
|
||||
end
|
||||
|
||||
it "raises an argument error for invalid input" do
|
||||
expect{subject.body = invalid_object}.to raise_error(
|
||||
ArgumentError, /invalid body/)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
|
Loading…
Reference in New Issue