TIL: How to use the Inline SVG gem with Vite Ruby/Rails

--

Create lib/inline_svg/vite_file_loader.rb and put the following code into it

# frozen_string_literal: true

module InlineSvg
class ViteFileLoader
def self.named(filename)
path = ViteRuby.instance.manifest.path_for(filename)

return fetch_from_dev_server(path) if ViteRuby.instance.dev_server_running?

Rails.public_path.join(path).read
end

def self.fetch_from_dev_server(path)
config = ViteRuby.config

path = "#{config.protocol}://#{config.host_with_port}#{path}"

URI.open(path) # rubocop:disable Security/Open
end
end
end

This will make inline_svg get the asset from the Vite Development Server in our Development environment. Otherwise it will just source the file directly from the filesystem.

In an initializer config/initializers/inline_svg.rb put the following

# frozen_string_literal: true

require 'inline_svg/vite_file_loader'

InlineSvg.configure do |config|
config.asset_file = InlineSvg::ViteFileLoader
end

Now put your icons into app/frontend/images and reference them with inline_svg('images/my_icon.svg').

You can of course create subfolders etc.

Enjoy!

--

--

Henrik Hauge Bjørnskov
Henrik Hauge Bjørnskov

Written by Henrik Hauge Bjørnskov

I build stuff at Relatel A/S, vivid traveller and gear junkie.

No responses yet