Class: Railsboot::AvatarComponent

Inherits:
Component
  • Object
show all
Defined in:
app/components/railsboot/avatar_component.rb

Constant Summary collapse

SHAPES =
["circle", "rounded", "square"].freeze
DEFAULT_SHAPE =
"circle".freeze
DEFAULT_SIZE =
32
COLORS =
["primary", "secondary", "light", "dark"].freeze
DEFAULT_COLOR =
"primary".freeze

Instance Method Summary collapse

Constructor Details

#initialize(src: "", letter: "", alt: "", shape: DEFAULT_SHAPE, size: DEFAULT_SIZE, color: DEFAULT_COLOR, href: "", **html_attributes) ⇒ AvatarComponent

Returns a new instance of AvatarComponent.



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'app/components/railsboot/avatar_component.rb', line 10

def initialize(src: "", letter: "", alt: "", shape: DEFAULT_SHAPE, size: DEFAULT_SIZE, color: DEFAULT_COLOR, href: "", **html_attributes)
  @alt = alt
  @shape = fetch_or_raise(shape, SHAPES)
  @size = size
  @color = fetch_or_raise(color, COLORS)
  @src = src.presence || letter_to_svg_base64(letter)
  @href = href
  @html_attributes = html_attributes

  @html_attributes[:class] = class_names(
    "position-relative",
    "d-inline-block",
    "bg-#{@color}",
    radius_class,
    html_attributes.delete(:class)
  )

  @html_attributes[:style] = [html_attributes[:style], "width: #{@size}px; height: #{@size}px; box-sizing: content-box;"].compact.join(" ")
end

Instance Method Details

#letter_to_svg_base64(letter = "") ⇒ Object (protected)



45
46
47
48
49
50
51
52
53
54
55
56
# File 'app/components/railsboot/avatar_component.rb', line 45

def letter_to_svg_base64(letter = "")
  font_color = (@color === "light") ? "black" : "white"
  svg_content = <<~SVG
    <svg width="100" height="100" xmlns="http://www.w3.org/2000/svg">
      <text x="50%" y="50%" alignment-baseline="middle" text-anchor="middle" font-family="Arial" font-size="40" dy=".1em" dominant-baseline="middle" fill="#{font_color}">
        #{letter}
      </text>
    </svg>
  SVG

  "data:image/svg+xml;base64,#{Base64.strict_encode64(svg_content)}"
end

#link?Boolean

Returns:

  • (Boolean)


39
40
41
# File 'app/components/railsboot/avatar_component.rb', line 39

def link?
  @href.present?
end

#radius_classObject



30
31
32
33
34
35
36
37
# File 'app/components/railsboot/avatar_component.rb', line 30

def radius_class
  shape_classes = {
    "circle" => "rounded-circle",
    "rounded" => "rounded-4",
    "square" => "rounded-0"
  }
  shape_classes[@shape]
end