Rails image asset tag helper - ruby-on-rails

In rails you can just a regular html img tag in your templates, what is the purpose of using an asset tag helper?
<%= image_tag "header.png" %>
vs.
<img src="header.png">

I think the image_tag also uses the asset path helpers. So it will automatically use '/assets/header.png'. Also if you have asset digest turned on I think it will automatically use '/assets/header-asdfasd.png' on production.

Actually, any image_tag would be transformed into HTML img tag.
I think Rails just provides some way to create HTML in Ruby/Rails way in case you are not a HTML guy, of course you can just use HTML img tag if you like.
Not only Rails, some other render utils, like Razor in C# , provide the similar feature.

Related

how to insert image in rails

Using Rails, I am creating my first web-site. And I have a problem like this: I can't insert an image in my page (index.html.erb).
I put an image named "main.png" in directory "app/assets/images", and wrote that:
<img src="main.png">
But my image isn't displayed correctly. What I'm doing not right?
You should use the provided helpers by Rails to "automagically" detect paths, fingerprints, ...:
<%= image_tag "main.png" %>
Anyway, I recommend you to read the asset pipeline guides to understand how the assets works in Rails: http://guides.rubyonrails.org/asset_pipeline.html
You should use Rails helpers as markets pointed out.
By the way, the name of the image file should be the same you use as the parameter of image_tag method. You are referencing your image as main.png when the image file is main.jpg
<%= image_tag "main.jpg" %>

Is there an advantage to using link_to over the anchor tag in Rails?

Don't these two do the same thing?
<%= link_to "Example", '#', class: "somestyle" %>
Example
If I'm writing a static .html.erb page, if everything else is written with HTML tags, doesn't it make sense to use HTML tags for links as well? I'm not sure why one should use a helper. Similarly, for linking style sheets, javascripts, etc.
For the link tags, it may not make a difference which way you go. Unless you're linking to more than "#". For instance, using a routed path.
For the stylesheets and javascript, I think you will need to continue to use the Rails helpers if you're taking advantage of the asset pipeline. If so, the hash in the filename changes at each asset compilation (I believe), and manually trying to edit the filename each time could become a pain.

How should I access the asset_url helper in the view

When I try to use asset_url in my view (Rails 3.2), I get a NoMethodError.
What do have to do to be able to use AssetUrlHelper's methods in my views?
To explain this a bit better and maybe find an alternative solutions: I need to get an "asset link" to file attachments created with carrierwave.
My model has an attachment which points to a file in my assets directory. I need to draw a link to this file.
= link_to model.name, model.attachment(:size)
gives me /myfiles/model/id/attachment/size.png (which is what is persisted by carrierwave)
= image_tag model.attachment(:size)
gives me the wanted http://static_host.com/.../size.png
but I have no need for an image tag, but the plain link to the file at the asset host.
The following works ok for me:
<%= link_to "link to asset", asset_path(article.image.url) %>
I'm using paperclip but I doubt it makes much difference
I think the helper asset_path belongs to asset files (like .css and .js) , not views. In views is proper to be used helpers like image_tag or stylesheet_include_tag. This is the idea behind the asset-pipeline - to ease reference to assets.

Acquire Asset Path from JavaScript

I need to display images on an HTML5 canvas that are in the Rails asset pipeline, but I need to know the path for the asset from JavaScript. I'm using js-routes for other parts of the application, but it doesn't appear to provide a way to get the path to something in the asset pipeline.
What's the correct way to obtain the path to a Rails asset (e.g., an image) from JavaScript?
In the Rails Asset Pipeline guide, they give an example of coding assets in your stylesheets by preprocessing the stylesheets with ERB. You can use the same technique with JavaScript, assuming you tack an .erb to the end of the filename:
var someAssetPath = "<%= asset_path('some_image.png') %>";
Checkout the js_assets(Javascript helper in rails projects) gem.
I think it is precisely what you need.
From the documentation:
Get the path to the template app/assets/javascripts/rubrics/views/index.html in javascript:
var path = asset_path('rubrics/views/index.html')
Why not add a data attribute for the path inside an element in your .erb file and then retrieve that with JQuery?
inside some_template.html.erb
<%= content_tag(:div, "", id: 'some-id', data:{path_to_asset: asset_path("some_image.png")}) %>
then in some_javascript.js
var assetPath = $("#some-id").data("pathToAsset");
For those using HAML you can do:
:javascript
var assetPath = "#{asset_path('some_image.jpg')}";
I came across the same issue in Rails 4.1 and used referencing rails assets in coffeescript for images. No additional libraries needed.
In my case, I wanted to get the stylesheet path and the hash that rails generates for cache busting made it impossible to hardcode.
What ended up working quite well for me is to assign an ID to the main stylesheet link element in the html (layout) and then use javascript to extract the href. If you want the base asset path, perhaps create a generic element with the data you need as an attribute.
Rendered HTML
<link rel="stylesheet" href="mypath/main.css" type="text/css" id="main-css">
JS
$("#main-css").attr("href"); // "mypath/main.css"

Rails with backbone-rails: asset helpers (image_path) in EJS files

I have a Rails 3.1 app that uses the codebrew/backbone-rails. In a .jst.ejs template, I would like to include an image, like so:
<img src="<%= image_path("foo.png") %>"/>
But of course the asset helpers are not available in JavaScript.
Chaining ERB (.jst.ejs.erb) does not work, because the EJS syntax conflicts with ERB.
Here is what I know:
The asset helpers are not available in the browser, so I need to run them on the server side.
I can work around the problem by making the server dump various asset paths into the HTML (through data attributes or <script> and JSON) and reading them back in JS, but this seems rather kludgy.
Is there a way to somehow use the asset helpers in EJS files?
There is a way, actually, to chain a .jst.ejs.erb file, although it's fairly undocumented, and I only found it through looking at the EJS test cases. You can tell EJS to use {{ }} (or [% %] or whatever else you want) instead of <% %>, and then ERB won't try to evaluate your EJS calls.
Make sure to require EJS somewhere in your code (I just included gem 'ejs' in my Gemfile), and then create an initializer (I called it ejs.rb) that includes the following:
EJS.evaluation_pattern = /\{\{([\s\S]+?)\}\}/
EJS.interpolation_pattern = /\{\{=([\s\S]+?)\}\}/
Then just make sure to rename your templates to .jst.ejs.erb, and replace your existing <% %> EJS-interpreted code with {{ }}. If you want to use something other than {{ }}, change the regular expressions in the initializer.
I wish there were an option in Sprockets to handle this through the config rather than having to explicitly include EJS, but as of the moment, there's no way to do that that I know of.
I can see two ways. Neither are great.
When you say <%%= variable %> then this is rendered by ERB as <%= variable %>, so you could double percent escape everything but the asset_tags and that would survive the trip through one ERB pass on the way to EJS.
If you find that too gross...
How about making a different javascript file, with an ERB extension, that defines your asset paths? And then use the asset pipeline to require that.
So say assets.js.erb defines something like:
MyAssets = {
'foo': <%= image_path("foo.png") %>,
...
}
And then require this somewhere near the top of your manifest. And then reference the globals however that works in EJS.
For those willing to try HAML instead of EJS: Using haml-coffee through haml_coffee_assets has worked well for me as well.
You can have the following in a .hamlc.erb file:
%img(src="<%= image_path('foo.png') %>")
(It still doesn't give you routing helpers though, only asset helpers.)
Ryan Fitzgerald was kind enough to post a gist of his JavaScript asset helpers (which get precompiled with ERB): https://gist.github.com/1406349
You can use corresponding Javascript helper via the following gem:
https://github.com/kavkaz/js_assets
Finally (after installing and configuring) you will be able to use it like this:
<img src="<%= asset_path("foo.png") %>"/>

Resources