Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Backport caching of the constant lookup #2079

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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'

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

concurrent is not an dependency of this project in this branch, so we need to add it as a dependency.


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