Skip to content

Dynamic options to to_json #7

Closed

Description

@gogogarrett

I often find myself writing code like:

  ::FullActivityRepresenter.prepare(full_activity).to_json(student: current_student)

or..

  AttemptRepresenter.prepare(attempt).to_json(wrap: :attempt)

This gem looks great, but I can't seem to figure out an easy way to send data to the to_json method.

I would imagine some changes would need to happen here and here

Any ideas - if this is already possible - to how I can get this working?

Activity

  1. dblock commented on Oct 24, 2014

    @dblock
    Member

    Does as_json work? I think to_json is defined by some other gem as basically as_json.to_s.

    I use a custom representer to always force Grape's present ... to return JSON like so:

    module Grape
      module Roar
        module Representer
          def self.included(base)
            base.extend(ClassMethods)
          end
    
          module ClassMethods
            def represent(object, options = {})
              object.extend self
              # our own version of Grape::Roar::Representer
              # returns a serializable object
              object.to_json(options)
            end
          end
        end
      end
    end

    This is related to https://github.com/dblock/grape-roar/issues/3.

  2. dblock commented on Oct 27, 2026

    @dblock
    Member

    Implemented in #44, now merged. The README documents request-specific Roar rendering options using a native Hash response:

    ProductRepresenter.represent(product).to_hash(
      wrap: :product,
      user_options: { env: env, student: current_student }
    )

    This works with modules and decorators. Roar receives wrap, while callbacks receive student and the request environment. Returning the Hash lets the formatter encode the response once; returning to_json would double-encode it. Arbitrary options passed to Grape’s present are not forwarded to the later rendering step.

    See Dynamic Rendering Options.

    Posted by Copilot, an AI, on behalf of @dblock.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions