Skip to content

Commit

Permalink
Reduce code execution in DetailsPresenter
Browse files Browse the repository at this point in the history
This presenter currently performs some of the same code in different
methods that determine the type of content in the field, and looks for
content types even when we know there won't be any present.

Therefore refactoring this presenter to perform as little code execution
as possible to order to determine the correct outcome for the content
type given.

This performance improvement is particularly important for GraphQL, as
we will be converting govspeak to HTML at render-time.
  • Loading branch information
brucebolt committed Feb 12, 2025
1 parent 8b5c7cd commit 216ad20
Showing 1 changed file with 17 additions and 16 deletions.
33 changes: 17 additions & 16 deletions app/presenters/details_presenter.rb
Original file line number Diff line number Diff line change
Expand Up @@ -22,29 +22,30 @@ def details

private

def govspeak_content?(value)
wrapped = Array.wrap(value)
wrapped.all? { |hsh| hsh.is_a?(Hash) } &&
wrapped.one? { |hsh| hsh[:content_type] == "text/govspeak" } &&
wrapped.none? { |hsh| hsh[:content_type] == "text/html" }
end

def html_content?(value)
wrapped = Array.wrap(value)
wrapped.all? { |hsh| hsh.is_a?(Hash) } &&
wrapped.one? { |hsh| hsh[:content_type] == "text/html" }
def content_type(value)
if value.one? { |hsh| hsh[:content_type] == "text/html" }
"text/html"
elsif value.one? { |hsh| hsh[:content_type] == "text/govspeak" }
"text/govspeak"
end
end

def recursively_transform_govspeak(obj)
return obj if !obj.respond_to?(:map) || html_content?(obj)
return render_govspeak(obj) if govspeak_content?(obj)

if obj.is_a?(Hash)
if obj.is_a?(Array) && obj.all?(Hash) && (obj_content_type = content_type(obj))
case obj_content_type
when "text/html"
obj
when "text/govspeak"
render_govspeak(obj)
end
elsif obj.is_a?(Array)
obj.map { |o| recursively_transform_govspeak(o) }
elsif obj.is_a?(Hash)
obj.transform_values do |value|
recursively_transform_govspeak(value)
end
else
obj.map { |o| recursively_transform_govspeak(o) }
obj
end
end

Expand Down

0 comments on commit 216ad20

Please sign in to comment.