Skip to content

Commit

Permalink
♻️ display default avatar if user doesn't have a profile picture (#83)
Browse files Browse the repository at this point in the history
  • Loading branch information
karinevieira authored May 4, 2024
1 parent b577f08 commit 256c448
Show file tree
Hide file tree
Showing 4 changed files with 21 additions and 14 deletions.
Binary file added app/assets/images/users/avatar.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
12 changes: 6 additions & 6 deletions app/components/users/avatar_component.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,16 @@

module Users
class AvatarComponent < ViewComponent::Base
attr_reader :image_url

def initialize(image_url:)
@image_url = image_url
def initialize(user:)
@user = user
end

private

def render?
image_url.present?
attr_reader :user

def image_url
user.profile.avatar.present? ? url_for(user.profile.avatar) : "users/avatar.png"
end
end
end
2 changes: 1 addition & 1 deletion app/pages/users/show_page.html.erb
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<div class="container mx-auto flex justify-center items-center mt-8">
<div class="bg-white p-4 sm:w-1/2 md:w-1/3 lg:w-1/4">
<%= render Users::AvatarComponent.new(image_url: "https://i.pravatar.cc/150?img=3") %>
<%= render Users::AvatarComponent.new(user: user) %>

<h1 class="text-xl font-bold text-center"><%= user.profile.display_name %></h1>
<p class="text-gray-600 text-center">@<%= user.profile.username %></p>
Expand Down
21 changes: 14 additions & 7 deletions spec/components/users/avatar_component_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,26 @@
require "rails_helper"

RSpec.describe Users::AvatarComponent, type: :component do
context "when image_url is given" do
context "when user has an avatar" do
it "renders user's avatar image" do
rendered = render_inline(described_class.new(image_url: "https://i.pravatar.cc/150?img=3"))
avatar = Rack::Test::UploadedFile.new(
Rails.root.join("spec/fixtures/files/image.png"), "image/png"
)
profile = create(:user_profile, avatar: avatar)
user = create(:user, profile: profile)

expect(rendered).to have_css("img[src*='https://i.pravatar.cc/150?img=3']")
rendered = render_inline(described_class.new(user: user))

expect(rendered).to have_css("img[src*='image.png']")
end
end

context "when image_url isn't given" do
it "doesn't render user's avatar image" do
rendered = render_inline(described_class.new(image_url: nil))
context "when user doesn't have an avatar" do
it "renders default avatar" do
user = create(:user)
rendered = render_inline(described_class.new(user: user))

expect(rendered.to_html).to be_empty
expect(rendered).to have_css("img[src*='users/avatar']")
end
end
end

0 comments on commit 256c448

Please sign in to comment.