Skip to content

Cannot Memoize Methods #107

Open
Open

Description

@richmolj
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?

Activity

  1. Startouf commented on Dec 12, 2019

    @Startouf

    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.

  2. ClayShentrup commented on Jun 20, 2020

    @ClayShentrup

    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
  3. wuarmin commented on Jun 21, 2020

    @wuarmin

    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.

  4. ClayShentrup commented on Jun 21, 2020

    @ClayShentrup

    You could implement a decorator/presenter pattern

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

  5. wuarmin commented on Jun 23, 2020

    @wuarmin

    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.

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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions