Skip to content

Truncate Formatter #372

@jonmchan

Description

@jonmchan

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..."
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions