Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Inline SVG for Rails
# Put this method in your helper file to render inline SVG
def inline_svg(path)
file = File.open("app/assets/images/#{path}", "rb")
raw file.read
end
@davidwmartin

This comment has been minimized.

Show comment Hide comment
@davidwmartin

davidwmartin Sep 24, 2013

This is extremely helpful sir, thank you very much.

This is extremely helpful sir, thank you very much.

@p886

This comment has been minimized.

Show comment Hide comment
@p886

p886 May 5, 2014

Thanks for the snippet, it is good practice to close a file after you use it. I would therefore use the block form of File#open so that the file automatically get's closed after we read from it:

def inline_svg(path)
    File.open("app/assets/images/#{path}", "rb") do |file|
    raw file.read
  end
end

p886 commented May 5, 2014

Thanks for the snippet, it is good practice to close a file after you use it. I would therefore use the block form of File#open so that the file automatically get's closed after we read from it:

def inline_svg(path)
    File.open("app/assets/images/#{path}", "rb") do |file|
    raw file.read
  end
end
@datenimperator

This comment has been minimized.

Show comment Hide comment
@datenimperator

datenimperator Jul 5, 2015

Instead of hard coding the path to app/assets/images I suggest to let the asset pipeline manage the file location. Use Rails.application.assets.find_asset(path).to_s instead of reading the file directly.

Instead of hard coding the path to app/assets/images I suggest to let the asset pipeline manage the file location. Use Rails.application.assets.find_asset(path).to_s instead of reading the file directly.

@dkam

This comment has been minimized.

Show comment Hide comment
@dkam

dkam Nov 4, 2015

Combining all this, I added this to my application helper:

  def inline_svg(path)
    raw Rails.application.assets.find_asset(path + '.svg').to_s
  end

dkam commented Nov 4, 2015

Combining all this, I added this to my application helper:

  def inline_svg(path)
    raw Rails.application.assets.find_asset(path + '.svg').to_s
  end
@kangkyu

This comment has been minimized.

Show comment Hide comment
@kangkyu

kangkyu Mar 30, 2016

Rails.application.assets became nil when config.assets.compile = false on production. Does it matter?

kangkyu commented Mar 30, 2016

Rails.application.assets became nil when config.assets.compile = false on production. Does it matter?

@saroar

This comment has been minimized.

Show comment Hide comment
@saroar

saroar Aug 9, 2016

How to upload an sag to AWS S3 using Carrierwave? in my rails add, any help will be appreciated thanks

saroar commented Aug 9, 2016

How to upload an sag to AWS S3 using Carrierwave? in my rails add, any help will be appreciated thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment