-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Make serializing to different formats trivial
By adding formats to `Serializer::MIME_TYPES` and a `to_#{format}`.
- Loading branch information
Showing
4 changed files
with
92 additions
and
13 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
require "yaml" | ||
require "granola/rack" | ||
|
||
class BaseSerializer < Granola::Serializer | ||
MIME_TYPES[:yaml] = "application/x-yaml".freeze | ||
|
||
def to_yaml(**opts) | ||
YAML.dump(serialized) | ||
end | ||
end | ||
|
||
User = Struct.new(:name, :age) | ||
|
||
class UserSerializer < BaseSerializer | ||
def serialized | ||
{ "name" => object.name, "age" => object.age } | ||
end | ||
end | ||
|
||
class Context | ||
include Granola::Rack | ||
end | ||
|
||
prepare do | ||
@user = User.new("John Doe", 25) | ||
end | ||
|
||
setup { Context.new } | ||
|
||
test "allows rendering as a different format" do |context| | ||
status, headers, body = context.granola(@user, as: :yaml) | ||
|
||
assert_equal 200, status | ||
assert_equal "application/x-yaml", headers["Content-Type"] | ||
|
||
assert_equal( | ||
{ "name" => "John Doe", "age" => 25 }, | ||
YAML.load(body.to_a.first) | ||
) | ||
end |