Skip to content

Commit

Permalink
Merge 098b2bb into 2e31a14
Browse files Browse the repository at this point in the history
  • Loading branch information
zlx committed Apr 16, 2014
2 parents 2e31a14 + 098b2bb commit 479b787
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 3 deletions.
33 changes: 31 additions & 2 deletions lib/active_model/serializer.rb
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,22 @@ module ActiveModel
class Serializer
include Serializable

class_attribute :cache
class_attribute :perform_caching

@mutex = Mutex.new

class << self
def inherited(base)
base._root = _root
base.perform_caching = false
base._attributes = (_attributes || []).dup
base._associations = (_associations || {}).dup
end

def cached(value = true)
self.perform_caching = value
end

def setup
@mutex.synchronize do
Expand Down Expand Up @@ -122,11 +130,32 @@ def json_key
end

def attributes
filter(self.class._attributes.dup).each_with_object({}) do |name, hash|
hash[name] = send(name)
if perform_cached?
if cache.read(expand_cache_key([self.class.to_s.underscore, cache_key, 'attributes-json']))
p "Fetch Cache: #{expand_cache_key([self.class.to_s.underscore, cache_key, 'attributes-json'])}"
else
p "Write Cache: #{expand_cache_key([self.class.to_s.underscore, cache_key, 'attributes-json'])}"
end
cache.fetch expand_cache_key([self.class.to_s.underscore, cache_key, 'attributes-json']) do
filter(self.class._attributes.dup).each_with_object({}) do |name, hash|
hash[name] = send(name)
end
end
else
filter(self.class._attributes.dup).each_with_object({}) do |name, hash|
hash[name] = send(name)
end
end
end

def perform_cached?
perform_caching && cache && respond_to?(:cache_key)
end

def expand_cache_key(*args)
ActiveSupport::Cache.expand_cache_key(args)
end

def associations
associations = self.class._associations
included_associations = filter(associations.keys)
Expand Down
4 changes: 4 additions & 0 deletions lib/active_model/serializer/railtie.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,9 @@ class Railtie < Rails::Railtie
require 'active_model/serializer/generators/serializer/scaffold_controller_generator'
require 'active_model/serializer/generators/resource_override'
end

initializer "caching.active_model_serializer" do |app|
ActiveModel::Serializer.cache = Rails.cache
end
end
end
4 changes: 3 additions & 1 deletion lib/active_model_serializers.rb
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@
begin
require 'action_controller'
require 'action_controller/serialization'

require 'active_support'
require 'active_support/core_ext'

ActiveSupport.on_load(:action_controller) do
include ::ActionController::Serialization
end
Expand Down

0 comments on commit 479b787

Please sign in to comment.