Module: HeroiconHelper
- Defined in:
- lib/heroicon/rails/heroicon_helper.rb
Constant Summary collapse
- HEROICONS_PATH =
File.("assets/heroicons", __dir__)
Instance Method Summary collapse
-
#heroicon(name, type: "solid", **options) ⇒ String
Returns an SVG icon from the Heroicons library with customizable dimensions.
Instance Method Details
#heroicon(name, type: "solid", **options) ⇒ String
Returns an SVG icon from the Heroicons library with customizable dimensions.
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
# File 'lib/heroicon/rails/heroicon_helper.rb', line 11 def heroicon(name, type: "solid", **) # Allow strings or symbols for name and type arguments name = name.to_s type = type.to_s # Handle class attribute custom_class = .delete(:class) || "" # Handle style attribute style_attribute = .delete(:style) # Handle title attribute title_attribute = .delete(:title) # Handle data- attributes, filtering out anything that doesn"t start with "data-" data_attributes = .select { |key, _| key.to_s.start_with?("data-") } .except!(*data_attributes.keys) # Load the SVG icon gem_root = Gem::Specification.find_by_name("heroicon-rails").gem_dir icon_path = File.join(gem_root, "lib", "heroicon", "rails", "assets", "heroicons", type, "#{name}.svg") icon_content = File.read(icon_path) icon_doc = Nokogiri::HTML::DocumentFragment.parse(icon_content) svg = icon_doc.at_css("svg") # Apply custom css classes custom_width_class = custom_class[/\bw-\d+/] custom_height_class = custom_class[/\bh-\d+/] default_width = custom_width_class ? "" : (type == "mini" ? "w-5" : "w-6") default_height = custom_height_class ? "" : (type == "mini" ? "h-5" : "h-6") css_classes = "#{default_width} #{default_height} #{custom_class}".strip svg[:class] = css_classes unless css_classes.empty? # Apply style attribute if present svg[:style] = style_attribute if style_attribute # Enhance accessibility svg[:role] = "img" svg["aria-labelledby"] = "#{name}-icon" title_element = Nokogiri::XML::Node.new("title", icon_doc) title_element.content = title_attribute || name.humanize title_element[:id] = "#{name}-icon" svg.prepend_child(title_element) # Add custom data- attributes data_attributes.each do |key, value| svg[key] = value end icon_doc.to_html.html_safe rescue StandardError => e "Icon #{name} not found. Error: #{e.}" end |