Sha256: 8c1b091ebe6571365061cefba9d5842640381b3943f3cdb75885685694a4905c

Contents?: true

Size: 1.15 KB

Versions: 1

Compression:

Stored size: 1.15 KB

Contents

module Initials
  class SVG
    attr_reader :name, :limit, :size

    def initialize(name, limit: 3, 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
      @limit = limit
      @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-size: #{font_size}px; font-family: -apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, Oxygen-Sans, Ubuntu, Cantarell, \"Helvetica Neue\", 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, limit].map { |s| s[0].capitalize }.join
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

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