grape-roar icon indicating copy to clipboard operation
grape-roar copied to clipboard

Dynamic options to to_json

Open gogogarrett opened this issue 11 years ago • 1 comments

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?

gogogarrett avatar Oct 22 '14 23:10 gogogarrett

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.

dblock avatar Oct 24 '14 11:10 dblock