Maintain RTL version of stylesheets with rails asset pipeline - ruby-on-rails

Background
I want to enable right-to-left locales as well as left-to-right, but I only want to maintain a single set of stylesheets.
The idea is that calling application-rtl.css will serve a rtl-converted version of application.css (using r2).
This functionality has two use-cases:
development: serve dynamically, converting on the fly
production: have precompilation generate the -rtl versions (extending rake assets:precompile task)
So far, I've managed to implement a RTLConverter that enables me to serve all my stylesheets converted to RTL without having touched them at all:
config/initializers/rtl_converter.rb:
require "r2"
require "tilt"
class RTLConverter < Tilt::Template
def prepare; end
def evaluate(context, locals, &block)
R2.r2 #data
end
end
Rails.application.assets.register_preprocessor 'text/css', RTLConverter
You can also implement this as an engine for sprockets to only convert files having the .rtl extension:
Rails.application.assets.register_engine 'rtl', RTLConverter
My question
How can I hook into the asset pipeline in order to:
serving an on-the-fly converted version of any stylesheet with the name-postfix '-rtl' (look for the file without the postfix and serve a converted version of that)?
creating converted copies with the name-postfix '-rtl' of all stylesheets during precompilation
Notes:
The converter does not work in conjunction with the sass engine, but seems to work fine with less. It's been applied to a twitter-bootstrap based site and works like a charm.
The converter has not been tested in production.
If I can find a decent solution to this problem, I intend to create and maintain a gem and give it back to the community.

I would aim for just using CSS directly to handle the LTR-RTL differences. CSS can probably handle the job for you. In case you define your CSS as LTR, then, based on a CSS class you can override the stuff you want.
Per default, define your entire CSS stylesheet as LTR.
Put an extra css class on the body which handle the locale. For instance <body class="RTL">
Define all exceptions to the default by overriding with CSS classes prefixed by "RTL"
A short example. Original "default" styles:
body { direction: ltr; }
.sidebar { width: 200px; float: right; margin-left: 30px }
Then, overwrite relevant styles later in your css:
body.rtl { direction: rtl; }
.rtl .sidebar { float: right; margin-right: 30px; }
/*remember to 'reset' all defaults for example: */
.rtl .sidebar { margin-left: 0; }
With sass, you have a common place to define standard variables, for instance margin in the example above. Your mileage may vary. But to me, that sounds more simple than messing with asset pipeline.

Unfortunately, none of the other answers really suggested the solution I was looking for, so after digging into matters, I was able to come up with a simple gem that could flip the stylesheet based on the filename.
So by including that gem and serving up a version of the stylesheet with '-flipped' appended to the name, I am now able to serve an automatically flipped version both in dev and production.
Find the gem on rubygems.org: stylesheet_flipper
Find a usage description on gihub: monibuds/stylesheet_flipper

As far as I can tell, Sprockets does not expose any hooks into the path lookup mechanism to processors. Even if it did, I don't think you could invoke some generalized "read asset" method.
All in all, I fear that making AP do what you want would require some serious arm-twisting.
So here's a completely different idea. What if you:
Dropped on-the-fly asset processing altogether, even in development
Had a Guard task set up to
recompile assets when their sources change (I think this exists already)
generate the RTL versions of the compiled CSS
Push the compiled assets to production (gasp!)
In other words, maybe you could trade some of the AP features for increased flexibility?
(I'm not going for the bounty here because this is just an idea, not a solution)

Wrote about this issue a year ago:
http://amitkazmirsky.com/2011/05/29/dry-your-rtl-and-ltr-css-files-in-rails-with-sass/
Basically my approach was to write the css with direction as variables:
#user-box {
backgroud-color: white;
padding: 0 5px;
float: $dir;
}
#side-nav {
margin-#{$opdir}: 5px;
}

Related

How to refer to rails assets from stylesheets?

I have a background image:
app/assets/images/bg.jpg
It works ok in development with the stylesheet as:
body {
background: #111 url('bg.jpg') repeat-x;
color: #DDD;
font: normal 90% "Trebuchet MS",Verdana,sans-serif;
margin-left: 1.2em;
}
But in production it doesn't show and the logs show:
ActionController::RoutingError (No route matches [GET] "/assets/bg.jpg"):
When I am using html and js templates I can add .erb to add the rails pre-processing that will let me use things like paths and helpers, e.g. images_url
How can I either:
a) Do a similar thing with my stylesheet
b) Use a path that works in both dev and prod. I tried [nothing] and images/ and they didn't work.
In the newer versions of rails, when you have a .css.scss stylesheets you have available a couple of helpers that will help you achieve that (you don't have to use .erb at all) like image-path and image-url (please take a look at the helpers section here https://github.com/rails/sass-rails)
basically what you need to do to get it working is replace
background: #111 url('bg.jpg') repeat-x;
for this
background: #111 image-url('bg.jpg') repeat-x;
and thats it. (also add the scss extension if you haven't already)
Precompile
You'll want to make use of the asset_path_helpers, specifically asset_url with one of the Rails asset preprocessors (SCSS / SASS)
The problem you'll have in production is that Rails appends what's known as a "fingerprint" to the assets. This fingerprint serves to define the uniqueness of the precompiled files:
Fingerprinting is a technique that makes the name of a file dependent
on the contents of the file. When the file contents change, the
filename is also changed. For content that is static or infrequently
changed, this provides an easy way to tell whether two versions of a
file are identical, even across different servers or deployment dates.
This means that when you push to production (and by virtue, precompile) the assets, you'll end up with the "bg.png" in a totally different location than that which you're referencing in the standard file.
--
Helpers
The trick is to use a dynamic path helper with the preprocessors:
#app/assets/stylesheets/application.css.scss
body {
background: #111 asset-url('bg.jpg') repeat-x;
color: #DDD;
font: normal 90% "Trebuchet MS",Verdana,sans-serif;
margin-left: 1.2em;
}
This should work for you
The fix that worked for me was to have
background: #111 url('<%= image_path "bg.jpg" %>') repeat-x;
and name my file .erb as in default.scss.css.erb
The other approaches didn't work.

How to include twitter bootstrap in my Rails project manually (without using any gems)?

I'm learning Rails and want to play with Rails and Twitter Bootstrap. My Rails project layout is:
├─assets
│ ├─images
│ ├─javascripts
│ └─stylesheets
├─controllers
├─helpers
├─mailers
├─models
└─views
├─course
└─layouts
The Twitter Bootstrap layout is:
├─css
├─img
└─js
I know Bootstrap css file references its image file, such as:
[class*=" icon-"] {
display: inline-block;
width: 14px;
height: 14px;
*margin-right: .3em;
line-height: 14px;
vertical-align: text-top;
background-image: url("../img/glyphicons-halflings.png");
background-position: 14px 14px;
background-repeat: no-repeat;
margin-top: 1px;
}
So they must retain there relative position, or I have to change the CSS file. I want to know, if I don't want to use any Bootstrap related gems, what's the best way to place these Bootstrap files into my Rails project? Thanks.
First, you should probably move the Bootstrap source files to their appropriate locations in the assets folder in your Rails app - that is, CSS files in the stylesheets folder, JS in javascripts, and images in images.
As mentioned already, you'll need to change paths to images in Bootstrap's CSS. However, you'll need to make use of Rails' asset path helpers if you plan on using your app in production.
For example, background-image: url('../images/glyphicons-halflings.png'); is absolutely incorrect when using the asset pipeline. This will work fine in development, but as soon as you pre-compile assets for a production environment things won't work - Rails appends fingerprints to asset file names for caching purposes, which makes the URL above incorrect.
The correct way to code paths in your assets is outlined in the Rails Guide for the Asset Pipeline. If you're using CSS only, you should add the .erb extension to your filename (to get bootstrap.css.erb) and do something like this:
background-image: url(<%= asset_path 'glyphicons-halflings.png' %>);
If you are using SASS/SCSS, you can also use the built-in asset-path or image-path helpers. Again, this is mentioned in the guide I linked to above.
In the end, you probably should be using a gem, as this work will already be done for you. But, if you must, this should work well enough. Of course, if you ever want to update Bootstrap, you'll have to do this again.
I ran into the same trouble, and didn't want to have to install gems, etc.
There's a much easier solution.
Just override the icon selectors for background image in your custom CSS.
[class^="icon-"], [class*=" icon-"] {
background-image: url("/assets/img/glyphicons-halflings.png");
}
[class^="icon-white"], [class*=" icon-white"] {
background-image: url("/assets/img/glyphicons-halflings-white.png");
}
Put the glyphicons PNGs in app/assets/images/img/ (or wherever you want) and you're done.
You have to change every Glyphicons icon to the assets path. That's a lot of work. Also you have to use LESS, so the easiest way to use bootstrap with rails is using a gem. This is the gem that I use gem 'twitter-bootstrap-rails' this gem also includes font awesome so check this too
Redirect calls in routes.rb
get '/img/:name', to: redirect {|params, req| "/assets/#{params[:name]}.#{params[:format]}" }
This will redirect calls for /img to /assets
You can put the css and js files anywhere in your project as they don't reference each other, however, you will have to update the glypicon references in the css file.
In your case:
background-image: url("../images/glyphicons-halflings.png");
EDIT: I updated the path. I originally included "assets" which is incorrect with your given directory structure.

Background images do not render on Ruby on Rails application

I am attempting to have a image render in the background of a div with the class head.
My application view is written Haml and the body is defined as follows:
%body
.container
.head
.sixteen_columns
.top-nav
Included in my application stylesheet is:
.head {
background-image: url(/images/background_image.jpg);
width: 100%;
height: auto;
}
I have tried a number of variations to specify the path of the image and altered the image name several times but to no avail.
What is the issue?
Consider using the asset_path helper when referencing images in your stylesheet. Documentation may be found here (check out 2.2.1)In the context the CSS you listed you would heave
.head {
background-image:url(<%= asset_path 'background_image.jpg'%>);
width:100%;
height:auto;
}
Note: This requires that your style sheet be an erb.
Doing so offers a number of advantages over explicitly stating the path, one being that as the structure of rails application changes with new version releases, you will not need to change anything in your code in order for that image to be referenced properly.
This may seem like overkill just to reference an image but it's one of the many conventions of Rails that are difficult to get used but great! as your application grows and changes, hopefully enabling it to better endure the test of time.
Assuming you're using Rails 3.1 or beyond, and that you're using the asset pipeline properly for your images, you can include your image file by doing the following:
.head {
background-image: url(/assets/background_image.jpg);
width: 100%;
height: auto;
}
The reason for this is because of the way the asset pipeline works. It compiles your assets at run time and it places all of your assets in a folder called /assets/. It also ignores subfolder structuring and it just dumps everything into the root /assets/ folder, not /assets/subfolder/.
Try running
rails -v
from the console to confirm what version of Rails you're on.
It sounds like you're running a rails 2.x application, correct? That should mean that you're serving images, js etc from the /public directory. One important gotcha that tripped me up setting background images in css is that the paths you specify are relative to the directory the stylesheet is in(e.g /public/stylesheets), not the root directory of the project itself.
Have you tried changing the path to go up one directory from where the stylesheet is located?
.head {
background-image: url(../images/background_image.jpg);
width: 100%;
height: auto;
}
EDIT: What other paths to the bg image have you tried?
Some other possibilities could be:
background-image: url(images/background_image.jpg);
background-image: url('../images/background_image.jpg');
One other thing to check would be to load the view and examine the div in Google Chrome using the inspector (Ctrl Shift + I). Select the div and examine the styles Chrome is assigning to it.
Also, double check that it's still named background_image.jpg Can't tell you how many times I've gotten burned by some typo I overlooked ;)
Solution:
It turned out to be a combination of two things. I used this format for the background image:
background-image: url(../images/background_image.jpg);
However, the .head div was renbdering with a height of 0. I added a fixed height to test, and it all showed up perfectly. I can work with this from here.
Thank you all so much for the help!!
In rails 4 you can now use a css and sass helper image-url:
div.logo {background-image: image-url("logo.png");}
If your background images aren't showing up consider looking at how you're referencing them in your css files.

User theme switching with SASS - Ruby on Rails

So I have an rails admin system that will allow a user to choose a theme, basically a set of SASS color variables that will recompile application.css.scss with the new colors. How would be the best way of going about changing this when the user selects from a drop down and submits? I read some up on some problems with caching and recompiling but I'm not totally clear how to set it up.
Currently I have..
application.css.scss
#import "themes/whatever_theme";
#import "common";
#import "reset";
#import "base";
themes/_whatever_theme
$theme_sprite_path: '/images/sprite_theme_name.png';
$main_color:#009DDD;
$secondary_color:#b3d929;
$light_background:#f2f2f2;
$border_line:#e6e6e6;
$off_white:#f9f9f9;
$white:#ffffff;
$font_body:#565b59;
$font_headers:#363a36;
Say I have 5 different themes the user will switch between, it would be nice to set variable names for each theme in Rails then pass these down to SASS and change them on the fly and recompile. Is this the best way to go about this?
3 easy steps:
Compile all themes into different files upon deploy. This will take care of timestamping, zipping, etc.
Render page with default theme.
Use javascript to load alternate theme CSS.
No need to mess with dynamic compilation and all that.
To load a CSS dynamically you can use something like this:
function loadCSS(url) {
var cssfile = document.createElement("link");
cssfile.setAttribute("rel", "stylesheet");
cssfile.setAttribute("type", "text/css");
cssfile.setAttribute("href", url);
}
Sergio's answer is valid, but omits the sassy details and I'd used a slightly different approach.
You're using SASS in Rails- don't fight the current, be Railsy and let the asset pipeline precompile all your CSS. Unless you're trying to do something extreme like CSSZenGarden with hundreds of themes, or each theme is thousands of lines I'd recommend setting each theme as it's own CSS class rather than it's own file.
1kb of extra CSS in the rendered application.css file won't bog down your users
It's straightforward to switch theme classes with JQuery: $(".ThemedElement").removeClass([all your themes]).addClass("MyLittlePonyTheme");
As implied, you will have to tag the elements you want the update with the ThemedElement class
You could alternatively just change the class on your top level element and make liberal use of inheritance and the !important declaration, although I find the other approach more maintainable.
If you think you can manage your themes with classes rather than files, here's how we generate them with SASS. SASS doesn't support json style objects, so we have to reach way back and set up a bunch of parallel arrays with the theme properties. Then we iterate over each theme, substitute the dynamic properties into the auto generated theme class, and you're off to the races:
themes.css.scss
#import "global.css.scss";
/* iterate over each theme and create a CSS class with the theme's properties */
#for $i from 1 through 4{
/* here are the names and dynamic properties for each theme class */
$name: nth(("DefaultTheme",
"MyLittlePonyTheme",
"BaconTheme",
"MySpaceTheme"
), $i);
$image: nth(("/assets/themes/bg_1.png",
"/assets/themes/bg_2.png",
"/assets/themes/bg_3.png",
"/assets/themes/bg_4.png"
), $i);
$primary: nth((#7ca8cb,
#3c6911,
#d25d3a,
#c20d2c
), $i);
$font: nth((Rosario,
Helvetica,
Comic Sans,
WingDings
), $i);
/* Now we write our Theme CSS and substitute our properties when desired */
.#{$name}{
&.Picker{
background-image:url($image);
}
color: $primary;
.BigInput, h1{
color: $primary;
font-family: $font, sans-serif !important;
}
.Frame{
background-image:url($image);
}
.Blank:hover{
background-color:mix('#FFF', $primary, 90%) !important;
}
.BigButton{
background-color:$primary;
#include box-shadow(0,0,10px, $primary);
}
/* and so on... */
}
It's a bit of a hack, but it's served us really well. If your themes are uber complicated or you have too many of them it gets more painful to maintain.
One option is to simply load a set of custom css rules (your theme) after your application.css and let your theme override the default colors from application.css. You could just add a database column "theme" and load the css with this name dynamically like.
SASS is not designed for compiling dynamic data on the fly. If you want dynamic css processing, you could add a controller method called "custom_css" and make this respond to the css format and load this dynamically with inline variables, but I don't think SASS is meant to be used for it at all.
I believe that you could use erb to inline variables in sass. I'm not positive, but I think it would look something like this:
themes/_whatever_theme.sass.erb
$theme_sprite_path: '<%= Theme.sprite_path %>';
$main_color: <%= Theme.main_color %>;
$secondary_color: <%= Theme.secondary_color %>;
These should be created dynamically for each page load. I'm not sure how the caching would work here.

How to use these ruby based CSS stylsheet frameworks languages?

I read about many CSS related languages and tools which need ruby.
What is the purpose of these
languages and tool how these can save
time and improve our CSS coding.
What is the role in ruby language in
these languages and tool.
Will i have to install and learn
ruby language to use these languages and tool.
will i need ruby installed on
webserver where website will be
hosted.
I'm talking abut these languages
http://lesscss.org/
http://sass-lang.com/
http://compass-style.org/
some mentioned here:
http://www.ruby-toolbox.com/categories/css_frameworks.html
I'm on Windows XP PC , How can i use these Ruby based languages and which is preferred? I don't know ruby language.
the point
the point of these languages (i prefer, however frameworks or extensions) of css is to incorporate your workflow to your css saving you time. How?
Let's imagine, that you have div with class some-long-class-to-be-sure-what-it-does and that div has h3 child, p child, .some-other-class child and something else (span child).
Now, if you want to style all of them, you have to do something like this:
.some-long-class-to-be-sure-what-it-does { width: 120px; }
.some-long-class-to-be-sure-what-it-does h3 { font-size: 20px; }
.some-long-class-to-be-sure-what-it-does p { margin-bottom: 30px; }
.some-long-class-to-be-sure-what-it-does .some-other-class { width: 120px; }
to inform browser about (i.e.) only h3 of .some-long-class-to-be-sure-what-it-does has font-size: 20px;.
with most of these parsers/frameworks, you have (still just an example) nesting at hand:
.some-long-class-to-be-sure-what-it-does {
width: 120px;
# h3 { font-size: 20px; }
# p {
margin-bottom: 30px;
# .subclass { color: red; }
}
# .some-other-class { width: 120px; }
}
which gives you smaller css, easier to edit in a long run (this is subjective, you may find it's harder for you to work with).
Also, they extend css in other ways besides nesting: constants (assign something to #col1 and use it on three places, then you decide, that you need something lighter... bam! you edit it once), flags, output formatting and many more, so I guess you will find your way of using it.
how to us it
mostly, you don't install it on your PC, but rather on your server. Instead of classic CSS, you link your site with installed CSS parser/framework/language, which on every call calculates (or will use cached version if avalaible) normal css - but when you edit it, you edit simplified/extended version of your css.
Edit: you don't install it onto your PC as a USER, but you need to install it into your developing enviroment. If it's localhost on your PC, then yes, you install it in your PC - but not as a user, but on your locally running server.
Ruby?
I think, that for ruby, these extensions to css were first. But now you can find it for other languages aswell - I, as PHP programmer, have found Anthony Short's CSScaffold:
github with little description
http://github.com/anthonyshort/csscaffold
scaffold's website, currently offline
http://scaffoldframework.com/
edit: what's it's use?
In that try example you see counting with multiple constant. that way, if you change !sidebar from 200px to 300px, every part of your css recalculates with it. every place this constant is mentioned, wheter by itself or in calculation.
another:
SASS in .NET - Better CSS in .NET?
less css in .NET - http://www.dotlesscss.com/
You don't need anything on your PC, these should be installed on your webserver and you have to write css code according to frameworks' rules.
Once you do that when you deploy your webapp to server these frameworks compile your styles and convert them to traditional stylesheets.
As far as i know this is mostly what they do.
Sinan.

Resources