我正在为标签和翻译使用数据库驱动的解决方案,我想在序列化程序级别上对其进行缓存。这是我的序列化器。
class AppLabelSerializer < ActiveModel::Serializer
cache key: 'app_label', expires_in: 3.hours
attributes :id, :key, :label, :label_plural
def key
object.app_label_dictionary.key
end
end
问题是我需要为每种语言缓存标签,因此需要在键中的某处指定语言。我尝试了以下解决方案:
cache key: "#{scope.app_language.name}/app_label", expires_in: 3.hours
但是由于scope
某些原因,此处的值不可用。
我在AMS github页面上发布了一个问题,并与@joaomdmoura和@groyoh来回交流,直到我们提出了这个临时解决方案。它对我有效,直到AMS对最佳解决方案做出正式决定之前,它将一直有效。
module ActiveModel
class Serializer
class Adapter
def cache_key
key = @klass._cache_key
key = @cached_serializer.instance_exec &key if key.is_a?(Proc)
key ? "#{key}/#{@cached_serializer.object.id}-#{@cached_serializer.object.updated_at}" : @cached_serializer.object.cache_key
end
end
end
end
class AppLabelSerializer < ActiveModel::Serializer
cache key: ->(){ "#{scope.app_language.name}/app_labels" }, expires_in: 3.hours
attributes :id, :label, :label_plural
end
它看起来很有趣,但是是的,您只需将ActiveModel模块的扩展名直接粘贴到您现有的序列化文件中即可。
注意:这仅适用于v0.10.0.rc1
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句