Rails: How to access images in Javascript? - ruby-on-rails

i'm pretty new to Rails and have a little question:
How can i access images in Javascript? SCSS, ERB, ... have methods like "image_path", but i didn't find something similar for Javascript.
I need it to specify the image URLs for the firefly plugin:
$.firefly({images : ['???/1.jpg', '???/2.jpg'],total : 40});

if your image in /app/assets/images/ you can simply use
/assets/1.jpg
Similarly in css, you can use
url(/assets/1.jpg)
You can follow same thing when using in javascript.
$.firefly({images : ['/assets/1.jpg', '/assets/2.jpg'],total : 40});
Note: The above methods will cause problem when your rails app is in sub-directory. In that case use relative path. Asset pre-compilation will compile all assets in public/assets directory. so your structure may be like:
public
-assets
--images
---1.png
--javascripts
--stylesheets
---style.css
so from style.css, you can use relative path like ../images/1.png

When I needed to do this, I inserted the whatever image was required on the page under a div#class and set that class as hidden in my css. Then, in javascript, I could access the image from that div.
May not be ideal solution, but couldn't think of anything else because of asset pipeline.
Also, try accessing image from ./assets/image_name.jpg

Related

How to give image path in ruby on rails

I want to use an image that is located in app/assets/revolution/assets/01.png.
I'm not using the by default app/assets/images folder. I want to use my own folder name 'revolution' where I'v made my own assets folder.
How do I give the image path in my index view? I'm trying to do it like this:
<%= image_tag ('revolution/assets/01.png') %>
You need to put that revolution folder in assets path first then you will be able access files from it.
config.assets.paths << Rails.root.join("app/assets", 'revolution')
Than only you will be able to access file from assets path like below.
<%= image_tag('01.png') %>
If you do not want to put your folder in assets images path. We have 2 ways of doing same. Either move your folder to assets/images or to public path (rails ways) in both way you can easily access file.
I think what you need is the helper asset_url
http://api.rubyonrails.org/classes/ActionView/Helpers/AssetUrlHelper.html#method-i-asset_url
But you would strongly advise you to use the default folder if you want to do that.
#mudasobwa While it's true, you don't have to be such a d..k in your reply :/. It's not as if we never coded shit when discovering new languages / libs / concepts
#Gagan Gami
You could, but you would then avoid the asset pipeline and are going to have a huge cache problem with your browser the day you replace your file while keeping the name.

Rails 4 assets - two different digests getting generated

I clearly must be Doing Something Wrong here. I'm wrestling with the asset pipeline (again). I have a custom font, and it seems to me to get everything to compile properly I need to use asset_path() in multiple places, but it's having an unexpected effect.
I realize there are several ways to do this, but here's what I have currently:
In application.css.scss.erb:
#import "<%= asset_path("my-font.css") %>";
my-font.css's source file is app/assets/stylesheets/my-font.css.erb (it needs to be an .erb because I am also using asset_path() there as well).
In application.rb I am adding my-font.css to the precompile list.
config.assets.precompile << 'my-font.css'
When I clean out public/assets and run rake assets:precompile Everything's getting compiled, with digests, but the digest applied to the actual file is not the same as the digest calculated and put in to application.css.
The resulting file is
public/assets/my-font-2f25682a1ea904a866ef9f44101a5a2e.css but in public/assets/application-bba2edaee36771f4bdb5c89b8ec90aaf.css the reference to it is:
#import url(/assets/my-font-ed843d3b174ca427edf963e473ad9e9b.css);
I realize I'm probably using asset_path() more than I should, and also importing files via url() instead of requiring them, but this has gotten me the closest to having things working.
I suspect one of the digests is being calculated on my-font.css before it goes through ERB, and the other after, but I don't understand why nor how to fix it.
Suggestions?
I would guess that you're cleaning your assets just by emptying public/assets. That's not enough, you'll also need to empty your tmp/cache/assets, or just run rake assets:clobber to do both.
I've resolve this kind of dependency by injecting the raw contents of the asset you want to bundle into a composite asset like application.scss.erb. You need to explicitly declare the dependency (so that changes in my-fonts.css cause a regenerations of application.css) and then inject the contents:
application.scss.erb:
// Should be at Top of File
//= depend_on_asset my-fonts.css
//... wherever in the file you want the contents injected:
<%= environment['my-fonts.css'] %>
How does this work? During asset pipeline compilation, the environment here has a hash of all pre-compiled asset contents. This allows you to inject the compiled contents from my-fonts.css into your composite asset. Because we're manually injecting the value, we need to explicitly create a dependency to track this relationship via depend_on_asset.
One thing to keep in mind is that multiple asset pre-processors (SCSS, ERB, etc) are processed from the "outside in", so the contents of the my-fonts.css asset will be compiled/injected during the ERB processing as CSS output. They will be included within the asset before SCSS processing. This shouldn't pose a problem, because if this is an SCSS asset, any SCSS references will be compiled before injection into the parent asset.

Rails 4 image-path, image-url and asset-url no longer work in SCSS files

Are we supposed to use something else aside from image-url and others in Rails 4? They return different values that don't seem to make sense. If I have logo.png in /app/assets/images/logo.png and I do the following, this is what I get:
image-url("logo.png") -> url("/images/logo.png") #obviously doesn't work
image-path("logo.png") -> "/images/logo.png"
asset-url("logo.png") -> url("/logo.png")
Of course none of these work because they need at least /assets in front.
UPDATE: Actually, I just noticed, how do I access images in Rails 4? I have an image at /app/assets/images/logo.png. But if I go to any of the following URLs, I still don't see my image:
http://localhost:3000/assets/logo.png
http://localhost:3000/assets/images/logo.png
http://localhost:3000/logo.png
http://localhost:3000/images/logo.png
UPDATE 2: The only way I can bring up my logo.png is by moving it into the /app/assets/stylesheets directory and then pulling up:
http://localhost:3000/assets/logo.png
I just had this issue myself.
3 points that will hopefully help:
If you place images in your app/assets/images directory, then you should be able to call the image directly with no prefix in the path. ie. image_url('logo.png')
Depending on where you use the asset will depend on the method. If you are using it as a background-image: property, then your line of code should be background-image: image-url('logo.png'). This works for both less and sass stylesheets. If you are using it inline in the view, then you will need to use the built in image_tag helper in rails to output your image. Once again, no prefixing <%= image_tag 'logo.png' %>
Lastly, if you are precompiling your assets, run rake assets:precompile to generate your assets, or rake assets:precompile RAILS_ENV=production for production, otherwise, your production environment will not have the fingerprinted assets when loading the page.
Also for those commands in point 3 you will need to prefix them with bundle exec if you are running bundler.
Your first formulation, image_url('logo.png'), is correct. If the image is found, it will generate the path /assets/logo.png (plus a hash in production). However, if Rails cannot find the image that you named, it will fall back to /images/logo.png.
The next question is: why isn't Rails finding your image? If you put it in app/assets/images/logo.png, then you should be able to access it by going to http://localhost:3000/assets/logo.png.
If that works, but your CSS isn't updating, you may need to clear the cache. Delete tmp/cache/assets from your project directory and restart the server (webrick, etc.).
If that fails, you can also try just using background-image: url(logo.png); That will cause your CSS to look for files with the same relative path (which in this case is /assets).
I just found out, that by using asset_url helper you solve that problem.
asset_url("backgrounds/pattern.png", image)
I had a similar problem, trying to add a background image with inline css. No need to specify the images folder due to the way asset sync works.
This worked for me:
background-image: url('/assets/image.jpg');
Rails 4.0.0 will look image defined with image-url in same directory structure with your css file.
For example, if your css in assets/stylesheets/main.css.scss, image-url('logo.png') becomes url(/assets/logo.png).
If you move your css file to assets/stylesheets/cpanel/main.css.scss, image-url('logo.png') becomes /assets/cpanel/logo.png.
If you want to use image directly under assets/images directory, you can use asset-url('logo.png')
for stylesheets:
url(asset_path('image.jpg'))
In case anyone arrives looking for how to generate a relative path from the rails console
ActionView::Helpers::AssetTagHelper
image_path('my_image.png')
=> "/images/my_image.png"
Or the controller
include ActionView::Helpers::AssetTagHelper
image_path('my_image.png')
=> "/images/my_image.png"

load images from javascript

In my Grails app, I have a dir web-app/images/carousel/slides that contains files such as:
foo.png
foo.thumbnail.png
bar.png
bar.thumbnail.png
My app is using the resources Grails plugin, and the main images are loaded in a GSP using one of it's tags:
<r:img file="carousel/slides/foo.png"/>
which generates:
<img src="/myapp/static/images/carousel/slides/foo.png">
I attempt to load the thumbnail images from JavaScript by constucting a path such as /myapp/static/images/carousel/slides/foo.thumbnail.png. But when I attempt to display one of these images, I get a 404.
Similarly, if enter the following path in the browser's address bar
http://localhost:8080/myapp/static/images/carousel/slides/foo.png
the image displays correctly, but if I enter
http://localhost:8080/myapp/static/images/carousel/slides/foo.thumbnail.png
I get a 404. Why are my thumbnail images not available at the same path at runtime, given that they're in the same source directory? I suspect the answer has something to do with the fact that the main images are loaded using the resources framework whereas I attempt to load the thumbnails from JavaScript.
You mostly answered your own question: if you don't reference the images using resources in some way, then they don't get processed.
Your best bet is to create a resources module that contains a list of all the images. The add this resource to the page.
// grails-app/conf/CarouselResource.groovy
modules = {
carousel {
resource url:'/images/carousel/foo.jpg'
resource url:'/images/carousel/foo.thumbnail.jpg'
...
}
}
then in your GSP
<r:require module="carousel"/>
Now, the module description is a DSL, so you might be able to use some sort of file loop to automatically add all the files, but I'm not 100% sure how. You also might try something like '/images/carousel/**', but the docs don't say if that would work or not.
Also, I should mention, if you use any of the caching-based resources plugins, this won't help. You will then need to manually call r.img() and set it within your JavaScript, something like this (if it works):
<r:script>
var images = [
'${r.img(...)}'
];
</r:script>
This is because the URLs generated using, for example, cached-resources, are often hashes of the file content to allow for long-term caching. They usually are only indirectly related to the original filename.
Update based on comment below:
To load a common JS remotely, but include the images, you could do something like this. Realize, I don't know your carousel code, and you will almost certainly have to modify the carousel library to handle these changes.
<r:script>
window.carouselImages = [
{
image: '${r.external(url:'images/carousel/image1.jpg'}.encodeAsJavaScript();}',
thumbnail: '${r.external(url:'images/carousel/image1.thumbnail.jpg'}.encodeAsJavaScript();}'
},
...
];
</r:script>
<r:resource url="js/carousel.js"/>
Then in carousel.js you reference window.carouselImages to get your array of images. It also should be possible it flip the order, and use some method within carousel.js to add images, like this:
<r:script>
carousel.addImage('${r.external(url:'images/carousel/image1.jpg'}.encodeAsJavaScript();}', '${r.external(url:'images/carousel/image1.thumbnail.jpg'}.encodeAsJavaScript();}');
...
</r:script>
You can improve this by looping over the file list instead of encoding each image explicitly (and example was given in the JIRA I posted below).
Finally, if you aren't going to use any of the caching or file manipulation plugins (so the files always end up at the same URL), you could just simply loop over the files from within the controller or a service method, calling r.img() on each one. This would ensure that they are copied to the static directory. The return value from r.img() can be ignored.
You can use HTML5's data-* Attribute
<element data-*="somevalue">
Here is an example if your image is located at /grails-app/assets/images:
In page (i.e. index.gsp) you have to add the following:
And from the javascript all you have to do is:
<script>
var calImg = document.getElementById('calendar-icon').getAttribute('data-calendaricon');
</script>
Pretty straightforward, moreover it is a clean approach :)

How to disable default asset timestamps for some assets in rails?

There are some image assets on my site that will always remain static, and therefore do not need the timestamp that gets appended to the images. Is there a way to not append the timestamps for certain assets?
Why not just use the regular HTML <img> element for those images? It'll be marginally faster than going through the Rails' helper too.
From the Rails docs "You can enable or disable the asset tag timestamps cache. With the cache enabled, the asset tag helper methods will make fewer expense file system calls. However this prevents you from modifying any asset files while the server is running."
ActionView::Helpers::AssetTagHelper.cache_asset_timestamps = true
Solution 1 would work, except I still need it to use the asset host, and I don't want to hardcode it. Solution 2 does not work since that would affect all asset paths. I think what I should be doing is to combine using the img tag, but use rails to compute the asset host for me.
So in the end it would look something like this
<img src=\"#{#template.image_path("image.jpg}}\"/>
thanks for the idea!

Resources