Skip to content

Commit 0342ddc

Browse files
ericproulxclaude
andauthored
Add :md and :markdown formatters that render an object's to_markdown (#3025)
Rails 8.1 registers text/markdown as Mime[:md] and adds `render markdown: obj`, which calls obj.to_markdown. Grape::Formatter::Markdown is the same contract for Grape: an object answering to_markdown is rendered with it and a String is returned as is. Anything else raises Grape::Exceptions::InvalidFormatter, so a client that negotiated Markdown for a Hash body gets the default format instead of its #to_s. .md and .markdown are both common Markdown extensions, so :md and :markdown name the same format. Declaring either content type answers both extensions and both ?format= spellings: the Formatter middleware resolves the other name through ContentTypes::FORMAT_SYNONYMS to the one the API declared, so a formatter, parser or error formatter declared for that name applies too. The lookup runs only when the requested format is not declared, so the common path is unchanged. Grape::Formatter::Md, an empty subclass of Markdown, registers the same rendering under :md. Each class names its own format in the InvalidFormatter message, derived from the class name the way the registry derives its key. Neither is a default content type; an API opts in with `content_type :md, 'text/markdown; charset=utf-8'`. Errors keep the text error formatter, and a text/markdown request body passes through unparsed. Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent ae39fbb commit 0342ddc

10 files changed

Lines changed: 235 additions & 1 deletion

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
* [#2960](https://github.com/ruby-grape/grape/pull/2960): Lint every response of an API once under `lint!`, including the router's 404 and mounted Rack apps, instead of inside each endpoint's stack - [@ericproulx](https://github.com/ericproulx).
1010
* [#2966](https://github.com/ruby-grape/grape/pull/2966): Require Ruby 3.3.1, the first 3.3 release that parses anonymous argument forwarding from inside a block - [@ericproulx](https://github.com/ericproulx).
1111
* [#3008](https://github.com/ruby-grape/grape/pull/3008): Add the grape-on-rack app as a live-server memory profiling harness - [@ericproulx](https://github.com/ericproulx).
12+
* [#3025](https://github.com/ruby-grape/grape/pull/3025): Add `:md` and `:markdown` formatters that render an object's `to_markdown`, for APIs that declare a `text/markdown` content type - [@ericproulx](https://github.com/ericproulx).
1213
* [#3029](https://github.com/ruby-grape/grape/pull/3029): Add a built-in `:jsonl` (JSON Lines) format that streams an Enumerator body - [@ericproulx](https://github.com/ericproulx).
1314
* Your contribution here.
1415

‎README.md‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3351,6 +3351,30 @@ Built-in formatters are the following.
33513351
* `:serializable_hash`: use object's `serializable_hash` when available, otherwise fallback to `:json`
33523352
* `:binary`: data will be returned "as is"
33533353
* `:jsonl`: one line per element of an Array or Enumerator, otherwise one line, each rendered as `:json` renders it. Not a default content type, see [JSON Lines](#json-lines)
3354+
* `:md`, `:markdown`: use object's `to_markdown` when available, return a String "as is", otherwise raise `Grape::Exceptions::InvalidFormatter`. Not default content types, see [Serving Markdown](#serving-markdown)
3355+
3356+
#### Serving Markdown
3357+
3358+
`:md` and `:markdown` are not among the default content types. Declare either one to answer clients that ask for Markdown, such as LLM agents sending `Accept: text/markdown`.
3359+
3360+
```ruby
3361+
class API < Grape::API
3362+
content_type :json, 'application/json'
3363+
content_type :md, 'text/markdown; charset=utf-8'
3364+
default_format :json
3365+
3366+
get '/pages/:id' do
3367+
Page.find(params[:id]) # renders with Page#to_markdown
3368+
end
3369+
end
3370+
```
3371+
3372+
* `GET /pages/1.md`, `GET /pages/1.markdown`, `GET /pages/1?format=md`, `?format=markdown` and `GET /pages/1` with an `Accept: text/markdown` header answer `text/markdown`.
3373+
* `:md` and `:markdown` name the same format: declaring either one answers both extensions, under the name declared. A request for `.markdown` on the API above negotiates `:md`, so a `formatter :md` of your own renders it too.
3374+
* `to_markdown` is the method Rails' `render markdown:` calls (Rails 8.1), so an object written for a Rails controller renders the same way in Grape.
3375+
* Grape does not convert anything else to Markdown. When the client negotiated Markdown, a body without `to_markdown` that is not a String answers in the default format instead; when the API pins `format :md`, it answers `500`.
3376+
* [RFC 7763](https://www.rfc-editor.org/rfc/rfc7763) makes `charset` a required parameter of `text/markdown`, hence `charset=utf-8`.
3377+
* Errors are rendered as plain text, which is valid Markdown.
33543378

33553379
#### Serving pre-rendered JSON
33563380

‎UPGRADING.md‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,15 @@ Grape now renders, parses and reports errors in JSON Lines under `:jsonl` ([#302
1313

1414
A formatter, parser or error formatter you register for `:jsonl` with `formatter`, `parser` or `error_formatter` still takes precedence.
1515

16+
#### Formats named `:md` and `:markdown` have a built-in formatter
17+
18+
`Grape::Formatter::Md` renders the `:md` format and `Grape::Formatter::Markdown` the `:markdown` one ([#3025](https://github.com/ruby-grape/grape/pull/3025)). Neither is a default content type, so only an API that declares one is affected. See [Serving Markdown](README.md#serving-markdown).
19+
20+
* An API that declared `content_type :md` (or `:markdown`) without a matching `formatter` used to send its bodies unchanged. A String still is. An object answering `to_markdown` is now rendered with it, and any other object raises `Grape::Exceptions::InvalidFormatter`: it answers in the default format when the client negotiated Markdown, and `500` otherwise.
21+
* `:md` and `:markdown` now name the same format. An API that declared one of them used to answer the other extension (and `?format=`) in its default format, or `406`; it now answers it in Markdown, under the name it declared.
22+
* A `formatter :md` or `formatter :markdown` of your own still takes precedence.
23+
* A formatter class of your own named `Md` or `Markdown` that inherits `Grape::Formatter::Base` now replaces Grape's globally, with a warning that `md` or `markdown` is already registered. Rename it, and declare it with `formatter :md, YourFormatter` (or `:markdown`) in the APIs that use it.
24+
1625
#### `logger` applies to the API it is set on
1726

1827
`logger` kept the logger in settings shared by the whole process, so setting it on one API replaced it on every other: two APIs that each set a logger both logged to whichever was set last.

‎lib/grape/content_types.rb‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,17 @@ module ContentTypes
1515

1616
MIME_TYPES = Grape::ContentTypes::DEFAULTS.except(:serializable_hash).invert.freeze
1717

18+
# Formats known by more than one name. A request naming one of them -- by
19+
# extension, +?format=+ or +default_format+ -- is served under whichever
20+
# the API declared, so declaring +:md+ answers +.markdown+ too, through
21+
# the formatter, parser and error formatter declared for +:md+. Both
22+
# spellings are keys: an extension arrives as a String, +default_format+
23+
# as a Symbol.
24+
FORMAT_SYNONYMS = {
25+
md: :markdown, 'md' => :markdown,
26+
markdown: :md, 'markdown' => :md
27+
}.freeze
28+
1829
def content_types_for(from_settings)
1930
from_settings.presence || DEFAULTS
2031
end

‎lib/grape/formatter/markdown.rb‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
# frozen_string_literal: true
2+
3+
module Grape
4+
module Formatter
5+
class Markdown < Base
6+
# Md inherits this, so the format named in the error comes from the class
7+
# name, the way Grape::Util::Registry derives the name each class is
8+
# registered under.
9+
def self.call(object, _env)
10+
return object.to_markdown if object.respond_to?(:to_markdown)
11+
return object if object.is_a?(String)
12+
13+
raise Grape::Exceptions::InvalidFormatter.new(object.class, name.demodulize.underscore)
14+
end
15+
end
16+
end
17+
end

‎lib/grape/formatter/md.rb‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
# frozen_string_literal: true
2+
3+
module Grape
4+
module Formatter
5+
# Registers Markdown's rendering under +md+ too, for an API that declares
6+
# +content_type :md+ rather than +:markdown+ (see
7+
# Grape::ContentTypes::FORMAT_SYNONYMS).
8+
class Md < Markdown
9+
end
10+
end
11+
end

‎lib/grape/middleware/formatter.rb‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -303,6 +303,9 @@ def negotiate_content_type(env)
303303
fmt = format_from_extension(env) || format_from_query(env) || format || format_from_header(env) || default_format
304304
return env[Grape::Env::API_FORMAT] = fmt.to_sym if content_type_for(fmt)
305305

306+
synonym = declared_synonym(fmt)
307+
return env[Grape::Env::API_FORMAT] = synonym if synonym
308+
306309
throw :error, Grape::Exceptions::ErrorResponse.new(status: 406, message: "The requested format '#{fmt}' is not supported.")
307310
end
308311

@@ -319,7 +322,16 @@ def format_from_extension(env)
319322
# A start and a length rather than an endless Range, which is an object
320323
# of its own built on every call. A length past the end is clamped.
321324
extension = try_scrub(request_path[dot_pos + 1, request_path.length])
322-
extension if content_type_for(extension)
325+
return extension if content_type_for(extension)
326+
327+
declared_synonym(extension)
328+
end
329+
330+
# The name the API declared +fmt+ under when the request used another
331+
# one for it (see Grape::ContentTypes::FORMAT_SYNONYMS), or nil.
332+
def declared_synonym(fmt)
333+
synonym = Grape::ContentTypes::FORMAT_SYNONYMS[fmt]
334+
synonym if synonym && content_type_for(synonym)
323335
end
324336

325337
# The extension is the tail of the request path, so PATH_INFO answers it

‎spec/grape/api_spec.rb‎

Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1723,6 +1723,103 @@ def query_request(body, content_type: 'application/json')
17231723
end
17241724
end
17251725

1726+
context 'with a Markdown content_type' do
1727+
let(:page) do
1728+
Class.new do
1729+
def to_markdown
1730+
"# Hello\n"
1731+
end
1732+
end.new
1733+
end
1734+
1735+
markdown_names = %w[md markdown]
1736+
1737+
markdown_names.each do |declared|
1738+
context "declared as #{declared}" do
1739+
before do
1740+
markdown_page = page
1741+
subject.content_type :json, 'application/json'
1742+
subject.content_type declared, 'text/markdown; charset=utf-8'
1743+
subject.default_format :json
1744+
1745+
subject.get('/page') { markdown_page }
1746+
subject.get('/hash') { { foo: 'bar' } }
1747+
subject.get('/error') { error!('error in markdown', 422) }
1748+
subject.get('/api_format') { env[Grape::Env::API_FORMAT].to_s }
1749+
end
1750+
1751+
it 'renders #to_markdown for an Accept: text/markdown header' do
1752+
get '/page', {}, 'HTTP_ACCEPT' => 'text/markdown'
1753+
expect(last_response.content_type).to eql 'text/markdown; charset=utf-8'
1754+
expect(last_response.body).to eq "# Hello\n"
1755+
end
1756+
1757+
markdown_names.each do |extension|
1758+
context "with the #{extension} extension" do
1759+
it 'renders #to_markdown' do
1760+
get "/page.#{extension}"
1761+
expect(last_response.content_type).to eql 'text/markdown; charset=utf-8'
1762+
expect(last_response.body).to eq "# Hello\n"
1763+
end
1764+
1765+
it "negotiates the #{declared} format" do
1766+
get "/api_format.#{extension}"
1767+
expect(last_response.body).to eq declared
1768+
end
1769+
1770+
it 'answers in the default format when the body has no Markdown form' do
1771+
get "/hash.#{extension}"
1772+
expect(last_response).to be_successful
1773+
expect(last_response.content_type).to eql 'application/json'
1774+
expect(last_response.body).to eq '{"foo":"bar"}'
1775+
end
1776+
1777+
it 'renders an error as text' do
1778+
get "/error.#{extension}"
1779+
expect(last_response.status).to eq 422
1780+
expect(last_response.content_type).to eql 'text/markdown; charset=utf-8'
1781+
expect(last_response.body).to eq 'error in markdown'
1782+
end
1783+
end
1784+
1785+
it "renders #to_markdown for ?format=#{extension}" do
1786+
get '/page', format: extension
1787+
expect(last_response.content_type).to eql 'text/markdown; charset=utf-8'
1788+
expect(last_response.body).to eq "# Hello\n"
1789+
end
1790+
end
1791+
end
1792+
end
1793+
1794+
it 'formats the markdown extension with a formatter declared for md' do
1795+
subject.content_type :md, 'text/markdown; charset=utf-8'
1796+
subject.formatter :md, ->(object, _env) { "custom #{object}" }
1797+
subject.get('/page') { 'page' }
1798+
1799+
get '/page.markdown'
1800+
expect(last_response.body).to eq 'custom page'
1801+
end
1802+
1803+
context 'when none is declared' do
1804+
before do
1805+
subject.content_type :json, 'application/json'
1806+
subject.default_format :json
1807+
subject.get('/page') { 'page' }
1808+
end
1809+
1810+
it 'answers the markdown extension in the default format' do
1811+
get '/page.markdown'
1812+
expect(last_response.content_type).to eql 'application/json'
1813+
expect(last_response.body).to eq '"page"'
1814+
end
1815+
1816+
it 'rejects ?format=markdown' do
1817+
get '/page', format: 'markdown'
1818+
expect(last_response.status).to eq 406
1819+
end
1820+
end
1821+
end
1822+
17261823
context 'env["api.format"]' do
17271824
before do
17281825
ct = content_type
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
# frozen_string_literal: true
2+
3+
describe Grape::Formatter::Markdown do
4+
it 'is registered under :markdown' do
5+
expect(Grape::Formatter.formatter_for(:markdown, nil)).to be(described_class)
6+
end
7+
8+
describe '.call' do
9+
it 'calls #to_markdown when the object responds to it' do
10+
page = Class.new do
11+
def to_markdown
12+
"# Hello\n"
13+
end
14+
end.new
15+
expect(described_class.call(page, {})).to eq("# Hello\n")
16+
end
17+
18+
it 'returns a String as is' do
19+
expect(described_class.call('# Hello', {})).to eq('# Hello')
20+
end
21+
22+
it 'raises Grape::Exceptions::InvalidFormatter for any other object' do
23+
expect { described_class.call({ a: 1 }, {}) }.to raise_error(Grape::Exceptions::InvalidFormatter, 'cannot convert Hash to markdown')
24+
end
25+
end
26+
end

‎spec/grape/formatter/md_spec.rb‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
# frozen_string_literal: true
2+
3+
describe Grape::Formatter::Md do
4+
it 'is registered under :md' do
5+
expect(Grape::Formatter.formatter_for(:md, nil)).to be(described_class)
6+
end
7+
8+
describe '.call' do
9+
it 'calls #to_markdown when the object responds to it' do
10+
page = Class.new do
11+
def to_markdown
12+
"# Hello\n"
13+
end
14+
end.new
15+
expect(described_class.call(page, {})).to eq("# Hello\n")
16+
end
17+
18+
it 'returns a String as is' do
19+
expect(described_class.call('# Hello', {})).to eq('# Hello')
20+
end
21+
22+
it 'raises Grape::Exceptions::InvalidFormatter for any other object' do
23+
expect { described_class.call({ a: 1 }, {}) }.to raise_error(Grape::Exceptions::InvalidFormatter, 'cannot convert Hash to md')
24+
end
25+
end
26+
end

0 commit comments

Comments
 (0)