Skip to content

Commit

Permalink
Use serializer over as_json (forem#13029)
Browse files Browse the repository at this point in the history
  • Loading branch information
atsmith813 committed Mar 19, 2021
1 parent 5f0c89d commit eb74102
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 15 deletions.
8 changes: 8 additions & 0 deletions app/serializers/search/username_serializer.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
module Search
class UsernameSerializer < ApplicationSerializer
attributes :id,
:name,
:profile_image_90,
:username
end
end
20 changes: 8 additions & 12 deletions app/services/search/postgres/username.rb
Original file line number Diff line number Diff line change
Expand Up @@ -11,22 +11,18 @@ class Username
].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
6 changes: 3 additions & 3 deletions spec/services/search/postgres/username_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
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

Expand All @@ -35,7 +35,7 @@
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)
Expand All @@ -52,7 +52,7 @@
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

0 comments on commit eb74102

Please sign in to comment.