active_model_serializers/lib/active_model/serializer/adapter/base.rb
Benjamin Fleischer 19de5f7722 Introduce Adapter::Base
Breaking change:
- Adapters now inherit Adapter::Base
- 'Adapter' is now a module, no longer a class
Why?

- using a class as a namespace that you also inherit from is complicated and circular at time i.e.
  buggy (see https://github.com/rails-api/active_model_serializers/pull/1177)
- The class methods on Adapter aren't necessarily related to the instance methods, they're more
    Adapter functions
- named `Base` because it's a Rails-ism
- It helps to isolate and highlight what the Adapter interface actually is
2015-09-20 12:26:04 -05:00

59 lines
1.4 KiB
Ruby

module ActiveModel
class Serializer
module Adapter
class Base
# Automatically register adapters when subclassing
def self.inherited(subclass)
ActiveModel::Serializer::Adapter.register(subclass)
end
attr_reader :serializer, :instance_options
def initialize(serializer, options = {})
@serializer = serializer
@instance_options = options
end
def serializable_hash(_options = nil)
fail NotImplementedError, 'This is an abstract method. Should be implemented at the concrete adapter.'
end
def as_json(options = nil)
hash = serializable_hash(options)
include_meta(hash)
hash
end
def fragment_cache(*_args)
fail NotImplementedError, 'This is an abstract method. Should be implemented at the concrete adapter.'
end
def cache_check(serializer)
CachedSerializer.new(serializer).cache_check(self) do
yield
end
end
private
def meta
serializer.meta if serializer.respond_to?(:meta)
end
def meta_key
serializer.meta_key || 'meta'.freeze
end
def root
serializer.json_key.to_sym if serializer.json_key
end
def include_meta(json)
json[meta_key] = meta if meta
json
end
end
end
end
end