Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cannot Memoize Methods #107

Open
richmolj opened this issue Aug 21, 2018 · 5 comments
Open

Cannot Memoize Methods #107

richmolj opened this issue Aug 21, 2018 · 5 comments

Comments

@richmolj
Copy link
Contributor

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?

@Startouf
Copy link

Startouf commented Dec 12, 2019

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.

@ClayShentrup
Copy link

ClayShentrup commented Jun 20, 2020

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

@wuarmin
Copy link

wuarmin commented Jun 21, 2020

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.

@ClayShentrup
Copy link

You could implement a decorator/presenter pattern

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

@wuarmin
Copy link

wuarmin commented Jun 23, 2020

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
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants