Skip to content

Commit

Permalink
Merge pull request #2079 from dylanahsmith/backport-serializers-cache
Browse files Browse the repository at this point in the history
Backport caching of the constant lookup
  • Loading branch information
rafaelfranca authored Mar 15, 2017
2 parents c2565ed + d58a6e1 commit 1e04d11
Show file tree
Hide file tree
Showing 4 changed files with 18 additions and 2 deletions.
1 change: 1 addition & 0 deletions active_model_serializers.gemspec
Original file line number Diff line number Diff line change
Expand Up @@ -21,5 +21,6 @@ Gem::Specification.new do |gem|
gem.required_ruby_version = ">= 1.9.3"

gem.add_dependency "activemodel", ">= 3.2"
gem.add_dependency "concurrent-ruby", "~> 1.0"
gem.add_development_dependency "rails", ">= 3.2"
end
6 changes: 5 additions & 1 deletion lib/active_model/serializable.rb
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,11 @@ def serializable_data
end

def namespace
get_namespace && Utils._const_get(get_namespace)
if module_name = get_namespace
Serializer.serializers_cache.fetch_or_store(module_name) do
Utils._const_get(module_name)
end
end
end

def embedded_in_root_associations
Expand Down
10 changes: 9 additions & 1 deletion lib/active_model/serializer.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
require 'active_model/serializer/config'

require 'thread'
require 'concurrent/map'

module ActiveModel
class Serializer
Expand Down Expand Up @@ -65,7 +66,10 @@ def serializer_for(resource, options = {})
ArraySerializer
end
else
_const_get build_serializer_class(resource, options)
klass_name = build_serializer_class(resource, options)
Serializer.serializers_cache.fetch_or_store(klass_name) do
_const_get(klass_name)
end
end
end

Expand Down Expand Up @@ -100,6 +104,10 @@ def has_many(*attrs)
associate(Association::HasMany, *attrs)
end

def serializers_cache
@serializers_cache ||= Concurrent::Map.new
end

private

def strip_attribute(attr)
Expand Down
3 changes: 3 additions & 0 deletions lib/active_model_serializers.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@
ActionController::Base.send(:include, ::ActionController::Serialization)
ActionController::TestCase.send(:include, ::ActionController::SerializationAssertions)
end
ActionDispatch::Reloader.to_prepare do
ActiveModel::Serializer.serializers_cache.clear
end
end
rescue LoadError
# rails not installed, continuing
Expand Down

0 comments on commit 1e04d11

Please sign in to comment.