Use serializer over as_json (#13029)
This commit is contained in:
parent
5f0c89dbfe
commit
eb741029b7
3 changed files with 19 additions and 15 deletions
8
app/serializers/search/username_serializer.rb
Normal file
8
app/serializers/search/username_serializer.rb
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
module Search
|
||||
class UsernameSerializer < ApplicationSerializer
|
||||
attributes :id,
|
||||
:name,
|
||||
:profile_image_90,
|
||||
:username
|
||||
end
|
||||
end
|
||||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue