Menu

Avatar

YM
render Avatar.new(src: "https://avatars.githubusercontent.com/u/30733", size: :lg)
render Avatar.new(initials: "YM", size: :lg)

Installation

Add the component to your project

CLI

Run the following command in your terminal

bundle exec essence add avatar
Manually

Copy and paste the following code into your project

components/avatar.rb
# frozen_string_literal: true

class Components::Avatar < Components::Essence
  BASE = "relative border border-transparent rounded-full bg-gray-100 aspect-square inline-flex items-center justify-center font-medium text-gray-700 overflow-hidden"
  IMAGE_CLASSES = "absolute w-full h-full object-cover z-50"
  SIZES = {
    sm: "size-6 text-[0.5rem]",
    md: "size-8 text-xs",
    lg: "size-12 text-sm"
  }

  attr_reader :initials, :size

  def initialize(initials: nil, size: :md, **attributes)
    @initials  = initials
    @size = size
    super(**attributes)
  end

  def view_template(&)
    div(**attributes) do
      div { initials } if initials
      img(src: attributes[:src], alt: attributes[:alt], class: IMAGE_CLASSES) if attributes[:src]
      yield if block_given?
    end
  end

  private

  def initialize_merged_classes = merge_classes(BASE, SIZES[size], attributes[:class])
end

Reference

This is how you can use this component

Attribute

Description

size
Avatar size
Available values —
smmdlg