Tuesday, September 8, 2015

It wasn't off the rails... I was!

Remember last post? It wasn't Ruby running off the rails. I was just me?

It seems I forgot a basic rule: go through assets pipeline!

When you're dealing with non-public assets, always use the assets pipeline, for it is going to solve assets location disregarding the web context.

Consider the case of the last post again, so we can understand exactly what happened.

In my bootstrap carousel images I was saying something like

<img src="carousel/image001.jpg" />

When I was visiting the page by the root route "/" my src element was pointing correctly to the image resource and the image was displaying correctly. In my routes.rb the root route was

root 'welcome#index'

Rails maps this to the URI "/", of course. Then we should have "/" and "/welcome/index" routing to the same point, and so we have. but  just inside Rails, and this is the point here.

When I do not use assets pipeline, bu try to point to a certain asset myself, as I did, you bypass Rails and then your are depending on another thing: the we context! 

And, as it happens, the web contexts for "/" and "/welcome/index" are different, so my images disappeared in the second case, even when displaying correctly in the first one.

The solution?

Easy as pie! Do as I said and go through the assets pipeline. In other word, go through Rails framework and say something like

<%= image_tag('carousel/img001.jpg') %>

With this you'll be saying to Rails something like "Hey! Find my asset your way. It's your business, not mine!"

Hope this may help other in the future. And please, send me your doubts when you think Ruby is running off the rails. I can't tell you I'll have a solution for all cases, but I may tell you I'll research a lot before giving up.