jsonapi-serializable icon indicating copy to clipboard operation
jsonapi-serializable copied to clipboard

Cannot Memoize Methods

Open richmolj opened this issue 6 years ago • 5 comments

attribute :foo do
  memo_method
end

def memo_method
  @memo ||= 'adsf'
end

Will raise error RuntimeError: can't modify frozen ..., due to this #freeze call. Is there a downside to removing the freeze?

richmolj avatar Aug 21 '18 15:08 richmolj

Hey, any news on this ? What's the recommended way to perform memoisation in serializers ?

Right now our solution is to memoize on the model but this feels dirty.

Startouf avatar Dec 12 '19 14:12 Startouf

Yeah this is frustrating. I just do a presenter.

class SerializablePortalFile < JSONAPI::Serializable::Resource
  type('portal_files')

  attributes(:kind)

  attribute(:current_version) do
    @object.version
  end

  attribute(:fields) do
    @object.rows.each_with_index.map do |row, i|
      key = row.fetch('0')
      {
        name: key,
        value: row.fetch('1'),
        masked?: @object.masks.fetch(i)
      }
    end
  end

  def initialize(object:, **args)
    super(object: Presenter.new(object), **args)
  end

  # Adds helper methods to the PortalFile.
  class Presenter < SimpleDelegator
    def rows
      rows_including_empty_last_row.tap(&:pop)
    end

    def rows_including_empty_last_row
      contents_as_json.fetch(:rows)
    end

    def masks
      @masks ||= meta_data.fetch('masks')
    end
  end
end

ClayShentrup avatar Jun 20 '20 05:06 ClayShentrup

You could implement a decorator/presenter pattern, which is responsible for memoizing and used as model of the serializer. With that you keep your model clean and independent of jsonapi.

wuarmin avatar Jun 21 '20 06:06 wuarmin

You could implement a decorator/presenter pattern

Indeed that is exactly what my code does there. The presenter class is called Presenter.

ClayShentrup avatar Jun 21 '20 16:06 ClayShentrup

You could implement a decorator/presenter pattern

Indeed that is exactly what my code does there. The presenter class is called Presenter.

Oh sorry, I overlooked that. I had an experience with another json-api-serializing-gem with the same problem. In the meantime I don't see it as a disadvantage to implement presenters between the models and the view-serializers.

wuarmin avatar Jun 23 '20 06:06 wuarmin