Skip to content

Instantly share code, notes, and snippets.

@sorentwo
Created January 14, 2015 16:54
Show Gist options
  • Save sorentwo/61de18fbbc9fd5660f83 to your computer and use it in GitHub Desktop.
Save sorentwo/61de18fbbc9fd5660f83 to your computer and use it in GitHub Desktop.
Perforated Serializer
require 'readthis/expanders'
require 'perforated'
class PerforatedSerializer
attr_reader :relation, :scope, :serializer, :options
def initialize(relation, options = {})
@relation = relation
@scope = options.fetch(:scope)
@serializer = options.fetch(:each_serializer)
@options = options
end
def to_json(opts = {})
cached(opts).to_json(opts) do |model|
serializer.new(model, options)
end
end
def cached(opts = {})
if relation.any?
Perforated.new(relation, KeyStrategy.new(scope, opts))
else
opts[:rooted] ? {} : []
end
end
private
class KeyStrategy
attr_reader :scope
attr_accessor :rooted
def initialize(scope, rooted: false)
@scope = scope
@rooted = rooted
end
def expand_cache_key(object)
args = [scope.role]
args << 'rooted' if rooted
if object.respond_to?(:object) && !object.respond_to?(:cache_key)
args.unshift(object.object)
else
args.unshift(object)
end
Readthis::Expanders.expand_key(args)
end
end
end
class V3::SubmissionsSerializer < Api::ApiController
def index
render json: PerforatedSerializer.new(
submission_query.submissions.paginate(paginatation_params),
scope: current_user,
root: 'submissions',
each_serializer: serializer
).to_json(rooted: true)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment