Skip to content

Commit

Permalink
Merge pull request #136 from tarcieri/refactor/request-body-validation
Browse files Browse the repository at this point in the history
Refactor request body validation
  • Loading branch information
ixti committed May 26, 2014
2 parents 8aaefc5 + 7fda2e3 commit ce1fa3f
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 7 deletions.
17 changes: 11 additions & 6 deletions lib/http/request/writer.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,16 @@ class Writer
# CRLF is the universal HTTP delimiter
CRLF = "\r\n"

# Types valid to be used as body source
VALID_BODY_TYPES = [String, NilClass, Enumerable]

def initialize(socket, body, headers, headerstart) # rubocop:disable ParameterLists
@body = body
fail(RequestError, 'body of wrong type') unless valid_body_type
@socket = socket
@headers = headers
@request_header = [headerstart]
end

def valid_body_type
valid_types = [String, NilClass, Enumerable]
checks = valid_types.map { |type| @body.is_a?(type) }
checks.any?
validate_body_type!
end

# Adds headers to the request header from the headers array
Expand Down Expand Up @@ -74,6 +72,13 @@ def send_request_body
@socket << '0' << CRLF * 2
end
end

private

def validate_body_type!
return if VALID_BODY_TYPES.any? { |type| @body.is_a? type }
fail RequestError, "body of wrong type: #{@body.class}"
end
end
end
end
2 changes: 1 addition & 1 deletion spec/http/request/writer_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ def construct(body)
end

it "doesn't throw on a nil body" do
expect { construct [] }.not_to raise_error
expect { construct nil }.not_to raise_error
end

it "doesn't throw on a String body" do
Expand Down

0 comments on commit ce1fa3f

Please sign in to comment.