Sha256: 7e40a77101835058fe0370b7aa9fe6cadd712d11279cd8f7bbdff9d64429ee14

Contents?: true

Size: 1008 Bytes

Versions: 1

Compression:

Stored size: 1008 Bytes

Contents

module Initials
  class SVG
    attr_reader :name, :size

    def initialize(name, size: 32)
      raise Initials::Error.new("Name is not a string or empty") unless (name.respond_to?(:to_s) && name.to_s.length > 0)
      @name = name
      @size = size
    end

    def to_s
      svg = [
        "<svg width='#{size}' height='#{size}'>",
          "<circle cx='#{size / 2}' cy='#{size / 2}' r='#{size / 2}' fill='#{fill}' />",
          "<text x='50%' y='50%' fill='white' fill-opacity='0.75' dominant-baseline='central' text-anchor='middle' style='font: bold #{font_size}px sans-serif; user-select: none;'>",
            "#{initials}",
          "</text>",
        "</svg>"
      ].join

      svg.html_safe rescue svg
    end

    def fill
      hue = name.split("").sum { |c| c.ord } % 360
      "hsl(#{hue}, 40%, 40%)"
    end

    def font_size
      size/2 + size/16 - (initials.length * size/16)
    end

    def initials
      name.split(' ')[0, 3].map { |s| s[0].capitalize }.join
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
initials-0.2.2 lib/initials/svg.rb