Monday, March 3, 2014

CSS and Ruby on Rails

After a week working on Demigod project, I acknowledge that it is actually more interesting than I expected at the beginning. One of the Ruby on Rails features that I like the most was the way Haml (HTML Abstraction Markup Language) pages connect with CSS style sheets. I am used to write code in HTML, which syntax is well-known among programmers. Thus, once you want to declare a new DIV structure, and associate it with CSS styles, you should write something like this:

<div class='wrap'>
    <div class='right'>
        //HTML code
    </div>
    <div class='left'>
        //HTML code
    </div>
</div>

And create the new classes in your CSS file (let's call it: mystyle.css), for example:

.left {
    background-color: yellow;
    overflow: hidden;
    margin-top: 20px;
    width:25%;
}

.right {
    background-color: red;
    float: right;
    width: 95%;
}

Additionally, you need to specify in your HTML file thename of the CSS file (in this case: <link rel="stylesheet" type="text/css" href="mystyle.css"> . Fortunately, things are much easier with Ruby on Rails, because both the DIV and the associated class take the same identification, and the DIV tag does not need to be closed. So, the above code in HTML becomes the following one in Haml:

.wrap
   .right
    -# Haml code
  .left
    -# Haml code

Easier and cleaner! I also tested this feature using id's instead of classes (i.e. #left instead of .left in the style sheet), and it worked properly. Despite RoR uses SCSS files (Syntactically Awesome Stylesheets), the syntax is the same as the classic CSS. It only requires to set the same name to both the style sheet and the haml file where the style is utilized.Furthermore, you have to to leave the SCSS file in an specific directory:

project_name\app\assets\stylesheets\haml_page_name.css.scss

Finally, I would like to say just one general thing to take into account when programming in Ruby on Rails. In my case, more than 80% of the compilation errors came from code indentation issues. From my point of view, the easiest way to indent the code with no errors is to use always the tab key and avoid using the space key, because I quickly noticed RoR is especially indentation-sensitive.

No comments:

Post a Comment