jsonapi-serializable
jsonapi-serializable copied to clipboard
Cannot Memoize Methods
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?
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.
You could implement a decorator/presenter pattern
Indeed that is exactly what my code does there. The presenter class is called Presenter.
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.