Class: Coco::Icon

Inherits:
Component
  • Object
show all
Includes:
Concerns::AcceptsOptions
Defined in:
app/components/coco/base/icon/icon.rb

Constant Summary collapse

ICON_CACHE =
{}
InvalidIconError =
Class.new(StandardError)

Instance Method Summary collapse

Methods included from Concerns::AcceptsOptions

#accepted_options, #get_option_group

Constructor Details

#initialize(name: nil, **kwargs) ⇒ Icon

Returns a new instance of Icon.



20
21
22
# File 'app/components/coco/base/icon/icon.rb', line 20

def initialize(name: nil, **kwargs)
  @icon_name = name&.to_s&.tr("_", "-")
end

Instance Method Details

#custom? ⇒ Boolean

Returns:

  • (Boolean)


39
40
41
# File 'app/components/coco/base/icon/icon.rb', line 39

def custom?
  @_custom ||= File.exist?(custom_icon_path)
end

#custom_icon_path ⇒ Object



57
58
59
# File 'app/components/coco/base/icon/icon.rb', line 57

def custom_icon_path
  @_custom_icon_path ||= Coco::Engine.root.join("app/assets/build/coco/icons/custom/#{name}.svg")
end

#icon_data ⇒ Object



32
33
34
35
36
37
# File 'app/components/coco/base/icon/icon.rb', line 32

def icon_data
  ICON_CACHE[name] ||= {
    custom: custom?,
    svg: read_svg
  }
end

#icon_path ⇒ Object



53
54
55
# File 'app/components/coco/base/icon/icon.rb', line 53

def icon_path
  @_icon_path ||= Coco::Engine.root.join("app/assets/build/coco/icons/#{name}.svg")
end

#name ⇒ Object



24
25
26
# File 'app/components/coco/base/icon/icon.rb', line 24

def name
  @icon_name
end

#read_svg ⇒ Object



43
44
45
46
47
48
49
50
51
# File 'app/components/coco/base/icon/icon.rb', line 43

def read_svg
  if custom?
    File.read(custom_icon_path).html_safe
  elsif File.exist?(icon_path)
    File.read(icon_path).html_safe
  elsif Rails.env.development? || Rails.env.test?
    raise InvalidIconError, "`#{name}` is not a valid icon name"
  end
end

#svg ⇒ Object



28
29
30
# File 'app/components/coco/base/icon/icon.rb', line 28

def svg
  content || icon_data[:svg]
end