Skip to content

Commit

Permalink
Allow default headers passed to Granola::Rack#json
Browse files Browse the repository at this point in the history
❤️ @lucasefe for the idea. See #2 for discussion.
  • Loading branch information
foca committed Feb 27, 2015
1 parent 1c4dfe1 commit e105f0b
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 2 deletions.
9 changes: 7 additions & 2 deletions lib/granola/rack.rb
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,11 @@ def self.included(base)
# Granola::Serializer. This takes care of setting the `Last-Modified` and
# `ETag` headers if appropriate.
#
# You can customize the response tuple by passing the status and the default
# headers, as in the following example:
#
# json(user, status: 400, headers: { "X-Error" => "Boom!" })
#
# object - An object to serialize into JSON.
#
# Keywords:
Expand All @@ -23,15 +28,15 @@ def self.included(base)
# serializer class.
# status: The HTTP status to return on stale responses. Defaults to
# `200`.
# headers: A Hash of default HTTP headers. Defaults to an empty Hash.
# **json_options: Any other keywords passed will be forwarded to the
# serializer's `#to_json` call.
#
# Raises NameError if no specific serializer is provided and we fail to infer
# one for this object.
# Returns a Rack response tuple.
def json(object, with: nil, status: 200, **json_options)
def json(object, with: nil, status: 200, headers: {}, **json_options)
serializer = serializer_for(object, with: with)
headers = {}

if serializer.last_modified
headers["Last-Modified".freeze] = serializer.last_modified.httpdate
Expand Down
8 changes: 8 additions & 0 deletions test/rack_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -50,3 +50,11 @@ def initialize(env = {})
expected_last_modified = Time.at(987654321).httpdate
assert_equal expected_last_modified, headers["Last-Modified"]
end

test "allows passing default headers" do |context|
default_headers = { "Other-Header" => "Meow" }
status, headers, body = context.json(@person, headers: default_headers)

assert_equal "application/json", headers["Content-Type"]
assert_equal "Meow", headers["Other-Header"]
end

0 comments on commit e105f0b

Please sign in to comment.