Class: Anyicon::Icon

Inherits:
Common show all
Defined in:
lib/anyicon/icon.rb

Overview

The Icon class is responsible for managing the rendering of icons from various collections available on GitHub. It handles downloading and caching of icons to ensure they are available for use in a Ruby on Rails application.

Example usage:

icon = Anyicon::Icon.new(icon: 'fontawesome_regular:address-book')
icon.render

The class supports additional properties that can be passed in to customize the SVG elements.

Constant Summary collapse

ALLOWED_ATTRIBUTES =

Initializes a new Icon instance.

%w[
  class id style width height viewBox fill stroke
  stroke-width opacity transform title aria-label aria-hidden role
].freeze
DATA_ATTRIBUTE_PATTERN =
/\Adata-[\w-]+\z/

Constants inherited from Common

Common::ALLOWED_HOSTS

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Common

#fetch

Constructor Details

#initialize(icon = nil, **props) ⇒ Icon

Returns a new instance of Icon.



31
32
33
34
35
36
# File 'lib/anyicon/icon.rb', line 31

def initialize(icon = nil, **props)
  super()
  @icons = (icon || props[:icon]).to_s.split(",").map { |i| i.split(":") }
  @icons.reject! { |i| i.length < 2 }
  @props = props.select { |key, _| allowed_attribute?(key) }
end

Class Method Details

.clear_cache!Object

Clears the in-memory SVG cache.



167
168
169
# File 'lib/anyicon/icon.rb', line 167

def clear_cache!
  @svg_cache = {}
end

.render(*args, **kwargs) ⇒ String

Renders the SVG content for the specified icons.

Parameters:

  • kwargs (Hash)

    the parameters for initializing an Icon instance

Returns:

  • (String)

    the HTML-safe SVG content



154
155
156
# File 'lib/anyicon/icon.rb', line 154

def render(*args, **kwargs)
  new(*args, **kwargs).render
end

.svg_cacheHash

In-memory cache for raw SVG file contents, keyed by file path. Avoids repeated File.read + disk I/O for the same icon.

Returns:

  • (Hash)

    the SVG cache



162
163
164
# File 'lib/anyicon/icon.rb', line 162

def svg_cache
  @svg_cache ||= {}
end

Instance Method Details

#renderString

Renders the SVG content for the specified icons.

Returns:

  • (String)

    the HTML-safe SVG content



41
42
43
44
45
46
47
# File 'lib/anyicon/icon.rb', line 41

def render
  parts = @icons.map do |icon|
    ensure_icon_exists(icon)
    svg_content(icon)
  end
  ActiveSupport::SafeBuffer.new(parts.join)
end