Merge pull request #1272 from bf4/add_public_poro_base

Add PORO serializable base class: ActiveModelSerializers::Model
This commit is contained in:
Benjamin Fleischer
2015-10-20 12:50:05 -05:00
10 changed files with 85 additions and 43 deletions

View File

@@ -80,8 +80,8 @@ module ActiveModel::Serializer::Lint
# arguments (Rails 4.0) or a splat (Rails 4.1+).
# Fails otherwise.
#
# <tt>cache_key</tt> returns a (self-expiring) unique key for the object,
# which is used by the adapter.
# <tt>cache_key</tt> returns a (self-expiring) unique key for the object, and
# is part of the (self-expiring) cache_key, which is used by the adapter.
# It is not required unless caching is enabled.
def test_cache_key
assert_respond_to resource, :cache_key
@@ -92,6 +92,19 @@ module ActiveModel::Serializer::Lint
assert_includes [-1, 0], actual_arity, "expected #{actual_arity.inspect} to be 0 or -1"
end
# Passes if the object responds to <tt>updated_at</tt> and if it takes no
# arguments.
# Fails otherwise.
#
# <tt>updated_at</tt> returns a Time object or iso8601 string and
# is part of the (self-expiring) cache_key, which is used by the adapter.
# It is not required unless caching is enabled.
def test_updated_at
assert_respond_to resource, :updated_at
actual_arity = resource.method(:updated_at).arity
assert_equal actual_arity, 0, "expected #{actual_arity.inspect} to be 0"
end
# Passes if the object responds to <tt>id</tt> and if it takes no
# arguments.
# Fails otherwise.

View File

@@ -7,6 +7,9 @@ module ActiveModelSerializers
mattr_accessor :logger
self.logger = Rails.logger || Logger.new(IO::NULL)
extend ActiveSupport::Autoload
autoload :Model
module_function
# @note

View File

@@ -0,0 +1,39 @@
# ActiveModelSerializers::Model is a convenient
# serializable class to inherit from when making
# serializable non-activerecord objects.
module ActiveModelSerializers
class Model
include ActiveModel::Model
include ActiveModel::Serializers::JSON
attr_reader :attributes
def initialize(attributes = {})
@attributes = attributes
super
end
# Defaults to the downcased model name.
def id
attributes.fetch(:id) { self.class.name.downcase }
end
# Defaults to the downcased model name and updated_at
def cache_key
attributes.fetch(:cache_key) { "#{self.class.name.downcase}/#{id}-#{updated_at.strftime("%Y%m%d%H%M%S%9N")}" }
end
# Defaults to the time the serializer file was modified.
def updated_at
attributes.fetch(:updated_at) { File.mtime(__FILE__) }
end
def read_attribute_for_serialization(key)
if key == :id || key == 'id'
attributes.fetch(key) { id }
else
attributes[key]
end
end
end
end