From eb741029b7c96ae362ece8a62e78c28f65d0601a Mon Sep 17 00:00:00 2001 From: Alex Date: Fri, 19 Mar 2021 11:16:52 -0400 Subject: [PATCH] Use serializer over as_json (#13029) --- app/serializers/search/username_serializer.rb | 8 ++++++++ app/services/search/postgres/username.rb | 20 ++++++++----------- .../services/search/postgres/username_spec.rb | 6 +++--- 3 files changed, 19 insertions(+), 15 deletions(-) create mode 100644 app/serializers/search/username_serializer.rb diff --git a/app/serializers/search/username_serializer.rb b/app/serializers/search/username_serializer.rb new file mode 100644 index 000000000..03aea0782 --- /dev/null +++ b/app/serializers/search/username_serializer.rb @@ -0,0 +1,8 @@ +module Search + class UsernameSerializer < ApplicationSerializer + attributes :id, + :name, + :profile_image_90, + :username + end +end diff --git a/app/services/search/postgres/username.rb b/app/services/search/postgres/username.rb index ed3f04972..73faba6e1 100644 --- a/app/services/search/postgres/username.rb +++ b/app/services/search/postgres/username.rb @@ -11,22 +11,18 @@ module Search ].freeze def self.search_documents(term) - users = search_users(term) + results = ::User.search_by_username(term).limit(MAX_RESULTS).select(*ATTRIBUTES) - users.map do |user| - user.as_json(only: %i[id name username]) - .merge("profile_image_90" => user.profile_image_90) - end + serialize(results) end - def self.search_users(term) - ::User - .search_by_username(term) - .limit(MAX_RESULTS) - .select(*ATTRIBUTES) + def self.serialize(results) + Search::UsernameSerializer + .new(results, is_collection: true) + .serializable_hash[:data] + .pluck(:attributes) end - - private_class_method :search_users + private_class_method :serialize end end end diff --git a/spec/services/search/postgres/username_spec.rb b/spec/services/search/postgres/username_spec.rb index 9c1d29633..73ed9764f 100644 --- a/spec/services/search/postgres/username_spec.rb +++ b/spec/services/search/postgres/username_spec.rb @@ -13,7 +13,7 @@ RSpec.describe Search::Postgres::Username, type: :service do result = described_class.search_documents(user.username) expect(result.first.keys).to match_array( - %w[id name profile_image_90 username], + %i[id name profile_image_90 username], ) end @@ -35,7 +35,7 @@ RSpec.describe Search::Postgres::Username, type: :service do rhymes = create(:user, username: "rhymes") result = described_class.search_documents("ale") - usernames = result.map { |r| r["username"] } + usernames = result.pluck(:username) expect(usernames).to include(alex.username) expect(usernames).to include(alexsmith.username) @@ -52,7 +52,7 @@ RSpec.describe Search::Postgres::Username, type: :service do results = described_class.search_documents("alex") expect(results.size).to eq(max_results) - expect([alex.username, alexsmith.username]).to include(results.first["username"]) + expect([alex.username, alexsmith.username]).to include(results.first[:username]) end end end