Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use formatters for custom vendored content types. #1185

Merged
merged 1 commit into from
Oct 16, 2015

Conversation

tylerdooling
Copy link
Contributor

Summary

When using custom vendored content types the specified formatters were not being used because only the generalized type was being made available to match.

Grape::Middleware::Formatter#mime_array - when provided with accept header application/vnd.mycompany.upcase+txt - has previously returned

[ 'application/txt']

and now returns

['application/vnd.mycompany.upcase+txt',  'application/txt']

This allows Grape::Middleware::Formatter#format_from_header to match the custom type and proceed to use the custom formatter.

Example

class Hello < Grape::API
  content_type :upcase, 'application/vnd.mycompany.upcase+txt'
  formatter :upcase, ->(obj, env){ obj.upcase }
  content_type :dashed, 'application/vnd.mycompany.dashed+txt'
  formatter :dashed, ->(obj, env){ obj.tr(' ', '-') }

  get :test do
    'hello world'
  end
end
# Before
$ curl localhost:9292/test -H 'Accept: application/vnd.mycompany.upcase+txt'
# status 406

$ curl localhost:9292/test -H 'Accept: application/vnd.mycompany.dashed+txt'
# status 406

# After
$ curl localhost:9292/test -H 'Accept: application/vnd.mycompany.upcase+txt'
# Content-Type: application/vnd.mycompany.upcase+txt
# HELLO WORLD

$ curl localhost:9292/test -H 'Accept: application/vnd.mycompany.dashed+txt'
# Content-Type: application/vnd.mycompany.dashed+txt
# hello-world

@dblock
Copy link
Member

dblock commented Oct 16, 2015

This is great. Does it need a README update as well (probably)?

@tylerdooling
Copy link
Contributor Author

Thanks @dblock. I'm happy to add to the readme if you've got something in mind. My initial read of it seemed to describe this custom formatter behavior already in the API Formats section. I initially just tried to use it and found that it didn't work for these prefixed types.

dblock added a commit that referenced this pull request Oct 16, 2015
Use formatters for custom vendored content types.
@dblock dblock merged commit 9c8713d into ruby-grape:master Oct 16, 2015
@dblock
Copy link
Member

dblock commented Oct 16, 2015

I merged this, thanks.

@tylerdooling
Copy link
Contributor Author

Sure thing - glad to help.

@tylerdooling tylerdooling deleted the use-custom-formatters branch October 16, 2015 15:48
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants