-
Notifications
You must be signed in to change notification settings - Fork 35
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
Comments
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. |
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 |
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. |
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. |
Will raise error
RuntimeError: can't modify frozen ...
, due to this #freeze call. Is there a downside to removing the freeze?The text was updated successfully, but these errors were encountered: