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

Improve performance of fields_for method with memoization #2474

Open
wants to merge 3 commits into
base: 0-10-stable
Choose a base branch
from
Open
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
17 changes: 16 additions & 1 deletion lib/active_model/serializer/fieldset.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,25 @@
module ActiveModel
class Serializer
class Fieldset
CONCURRENT_MAP_AVAILABLE = defined?(Concurrent::Map)

def initialize(fields)
@raw_fields = fields || {}
@fields_for_cache = Concurrent::Map.new if CONCURRENT_MAP_AVAILABLE
end

def fields
@fields ||= parsed_fields
end

def fields_for(type)
fields[type.to_s.singularize.to_sym] || fields[type.to_s.pluralize.to_sym]
if CONCURRENT_MAP_AVAILABLE
@fields_for_cache.fetch_or_store(type) do
compute_fields_for(type)
end
else
compute_fields_for(type)
end
end

protected
Expand All @@ -28,6 +37,12 @@ def parsed_fields
{}
end
end

def compute_fields_for(type)
singular_type = type.to_s.singularize.to_sym
plural_type = type.to_s.pluralize.to_sym
fields[singular_type] || fields[plural_type]
end
end
end
end