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

Truncate Formatter #372

Open
jonmchan opened this issue Dec 21, 2022 · 0 comments
Open

Truncate Formatter #372

jonmchan opened this issue Dec 21, 2022 · 0 comments

Comments

@jonmchan
Copy link
Contributor

Do we have a wiki to stick this content into? Or maybe we can add it to the README.md?

I thought identifying how to truncate long fields may be useful for others as well.

For large character length fields that you wish to truncate and append ellipse (...), you can utilize the format_with function.

Code example:

  class MyEntity < Grape::Entity
    format_with(:truncate) { |str| str.truncate(50) }

    with_options(format_with: :truncate) do
      expose :summary
      expose :raw_content
    end
  end

This will render your content as following when the field is over 50 characters long:

{
      "summary": "adfasdf sdafjlksdaf kslafj lksdaf jlkdsfafdkasl...",
      "raw_content": "adfasdf sdafjlksdaf kslafj lksdaf jlkdsfafdkasl..."
}
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

No branches or pull requests

1 participant