Skip to content
Daniel Kehoe edited this page Nov 24, 2013 · 16 revisions

Foundation and Rails

by Daniel Kehoe

Last updated 24 November 2013

Foundation 5.0 and Rails 4.0. Shows how to set up a Rails application to use Zurb Foundation. Developers use Foundation to add attractive CSS styling and JavaScript effects to web applications. Zurb Foundation and other CSS “front-end” frameworks (such as Twitter Bootstrap) are toolkits that provide the kind of structure and convention that have made Rails popular for server-side (“back-end”) development.

If You Are New to Rails

If you’re new to Rails, see What is Ruby on Rails?, the book Learn Ruby on Rails, and recommendations for a Rails tutorial.

Learn Ruby on Rails

This article is excerpted from book Learn Ruby on Rails. Get the book for more on Rails and Foundation.

What is the RailsApps Project?

This is an article from the RailsApps project. The RailsApps project provides example applications that developers use as starter apps. Hundreds of developers use the apps, report problems as they arise, and propose solutions. Rails changes frequently; each application is known to work and serves as your personal “reference implementation” so you can stay up to date. Each is accompanied by a tutorial so there is no mystery code. Support for the project, including the example applications and the Rails Composer tool, comes from subscribers to the RailsApps tutorials.

Zurb Foundation Gem

Zurb Foundation provides a standard grid for layout plus dozens of reusable components for common page elements such as navigation, forms, and buttons. More importantly, it gives CSS the kind of structure and convention that makes Rails popular for back-end development. Zurb Foundation is packaged as a gem.

In your Gemfile, you’ve already added:

@ ruby
gem ‘compass-rails’, ‘~> 2.0.alpha.0’
gem ‘zurb-foundation’
@

and previously run $ bundle install.

Zurb Foundation requires the compass-rails gem which (at the time this was written) is available in a prerelease version for Rails 4.0.

Rather than following the installation instructions provided in the Foundation 4 Documentation, we’ll use the rails_layout gem to set up Zurb Foundation and create the files we need. Our approach is slightly different from the Zurb instructions but yields the same results.

Rails Layout Gem with Zurb Foundation

In the previous chapter, we used the rails_layout gem to configure the default application layout with HTML5 elements, navigation links, and flash messages. Now we’ll use the rails_layout gem to set up Zurb Foundation and generate new files for the application layout as well as the navigation and messages partials. The new files will replace the layout files we created in the previous chapter.

We’ll use the generator provided by the rails_layout gem uses to set up Foundation and add the necessary files. Run:

@ console
$ rails generate layout foundation4 —force
@

With the --force argument, the rails_layout gem will replace existing files.

The rails_layout gem will rename the file:

  • app/assets/stylesheets/application.css

to:

  • app/assets/stylesheets/application.css.scss

It will create the file:

  • app/assets/stylesheets/framework_and_overrides.css.scss

and modify the file:

  • app/assets/javascripts/application.js

The gem will replace four files:

  • app/views/layouts/application.html.erb
  • app/views/layouts/_messages.html.erb
  • app/views/layouts/_navigation.html.erb
  • app/views/layouts/_navigation_links.html.erb

It will also remove the file:

  • app/assets/stylesheets/simple.css

Let’s examine the files to see how our application is configured to use Zurb Foundation.

Renaming the application.css File

The rails_layout gem renamed the app/assets/stylesheets/application.css file as app/assets/stylesheets/application.css.scss. Note the .scss file extension. This will allow you to use the advantages of an improved syntax for your application stylesheet.

You learned earlier that stylesheets can use variables, mixins, and nesting of CSS rules when you use Sass.

Sass has two syntaxes. The most commonly used syntax is known as “SCSS” (for “Sassy CSS”), and is a superset of the CSS syntax. This means that every valid CSS stylesheet is valid SCSS as well. SCSS files use the extension .scss. The Sass project also offers a second, older syntax with indented formatting that uses the extension .sass. We’ll use the SCSS syntax.

You can use Sass in any file by adding the file extension .scss. The asset pipeline will preprocess any .scss file and expand it as standard CSS.

For more on the advantages of Sass and how to use it, see the Sass website or the Sass Basics RailsCast from Ryan Bates.

Before you continue, make sure that the rails_layout gem renamed the app/assets/stylesheets/application.css file as app/assets/stylesheets/application.css.scss. Otherwise you won’t see the CSS styling we will apply.

The application.css.scss File

In the previous chapter, I introduced the Rails asset pipeline.

Your CSS stylesheets get concatenated and compacted for delivery to the browser when you add them to this directory:

  • app/assets/stylesheets/

The asset pipeline helps web pages display faster in the browser by combining all CSS files into a single file (it does the same for JavaScript).

Let’s examine the file app/assets/stylesheets/application.css.scss:

@ sass
/*

  • This is a manifest file that’ll be compiled into application.css, which will include all the files
  • listed below.
    *
  • Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets,
  • or vendor/assets/stylesheets of plugins, if any, can be referenced here using a relative path.
    *
  • You’re free to add application-wide styles to this file and they’ll appear at the top of the
  • compiled file, but it’s generally better to create a new file per style scope.
    *
  • require_self
  • require_tree .
    */
    @

The app/assets/stylesheets/application.css.scss file serves two purposes.

First, you can add any CSS rules to the file that you want to use anywhere on your website. Second, the file serves as a manifest, providing a list of files that should be concatenated and included in the single CSS file that is delivered to the browser.

A Global CSS File

Any CSS style rules that you add to the app/assets/stylesheets/application.css.scss file will be available to any view in the application. You could use this file for any style rules that are used on every page, particularly simple utility rules such as highlighting or resetting the appearance of links. However, in practice, you are more likely to modify the style rules provided by Zurb Foundation. These modifications don’t belong in the app/assets/stylesheets/application.css.scss file; they will go in the app/assets/stylesheets/framework_and_overrides.css.scss file.

In general, it’s bad practice to place a lot of CSS in the app/assets/stylesheets/application.css.scss file (unless your CSS is very limited). Instead, structure your CSS in multiple files. CSS that is used on only a single page can go in a file with a name that matches the page. Or, if sections of the website share common elements, such as themes for landing pages or administrative pages, make a file for each theme. How you organize your CSS is up to you; the asset pipeline lets you organize your CSS so it is easier to develop and maintain. Just add the files to the app/assets/stylesheets/ folder.

A Manifest File

It’s not obvious from the name of the app/assets/stylesheets/application.css.scss file that it serves as a manifest file as well as a location for miscellaneous CSS rules. For most websites, you can ignore its role as a manifest file. In the comments at the top of the file, the *= require_self directive indicates that any CSS in the file should be delivered to the browser. The *= require_tree . directive (note the Unix “dot operator”) indicates any files in the same folder, including files in subfolders, should be combined into a single file for delivery to the browser.

If your website is large and complex, you can remove the *= require_tree . directive and specify individual files to be included in the file that is generated by the asset pipeline. This gives you the option of reducing the size of the application-wide CSS file that is delivered to the browser. For example, you might segregate a file that includes CSS that is used only in the site’s administrative section. In general, only large and complex sites need this optimization. The speed of rendering a single large CSS file is faster than fetching multiple files.

Zurb Foundation JavaScript

Zurb Foundation provides both CSS and JavaScript libraries.

Like the application.css.scss file, the application.js file is a manifest that allows a developer to designate the JavaScript files that will be combined for delivery to the browser.

The rails_layout gem modified the file app/assets/javascripts/application.js to include the Foundation JavaScript libraries:

@ js
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require foundation
//= require_tree .
$(function() {
$(document).foundation();
});
@

It added the directive //= require foundation before //= require_tree ..

The last three lines use jQuery to load the Foundation JavaScript libraries after the browser has fired a “DOM ready” event (which means the page is fully rendered and not waiting for additional files to download).

@ js
$(function() {
$(document).foundation();
});
@

Note that this configuration is different from the instructions provided in the Foundation 4 Documentation. In keeping with Rails best practices, we load the Foundation JavaScript libraries using the asset pipeline in the <head> section of the default application layout. Using the jQuery “DOM ready” event to load Foundation insures that Foundation is compatible with other jQuery plugins or JavaScript code.

Zurb Foundation CSS

The rails_layout gem added a file app/assets/stylesheets/framework_and_overrides.css.scss containing:

@ scss
// import the CSS framework
import "foundation"; . . . @@

The file app/assets/stylesheets/framework_and_overrides.css.scss is automatically included and compiled into your Rails application.css file by the *= require_tree . statement in the app/assets/stylesheets/application.css.scss file.

The @import "foundation"; directive will import the Foundation CSS rules from the Foundation gem.

You could add the Foundation @import code to the app/assets/stylesheets/application.css.scss file. However, it is better to have a separate app/assets/stylesheets/framework_and_overrides.css.scss file. You may wish to modify the Foundation CSS rules; placing changes to Foundation CSS rules in the framework_and_overrides.css.scss file will keep your CSS better organized.

In addition to the simple @import "foundation"; directive, the app/assets/stylesheets/framework_and_overrides.css.scss contains a collection of Sass mixins. We’ll look at these later in the chapter.

Using Foundation CSS Classes

Now that you’ve installed Zurb Foundation, you have a rich library of interactive effects you can add to your pages.

Take a look at the Foundation documentation to see your options. Here are just a few examples:

At a simpler level, Foundation provides a collection of carefully-crafted styling rules in the form of CSS classes. These are building blocks you use for page layout and typographic styling. For example, Foundation gives you CSS classes to set up rows and columns in a grid system.

Let’s take a closer look at the Foundation grid system.

Foundation Grid

By default, the Foundation grid is 940 pixels wide. Two grids are available; “small” for browsers less than 768 pixels in width, and “large” for all others. Start by designing for the small screen with the classes prefixed “small”; then add classes prefixed “large” to change the layout for a large screen. The layout will change when the browser width is less than 768 pixels wide.

The grid gives you 12 columns by default. You can organize your layout in horizontal and vertical sections using row and columns classes.

For example, you could use Foundation grid classes to set up an application layout with a footer as a row with two sections:

@ html



Copyright 2013 All rights reserved.

@

The Foundation row class will create a horizontal break. The footer will contain two side-by-side sections. The first will be four columns wide; the second will be eight columns wide.

To better understand the grid system with all its options, see the documentation for the Foundation Grid.

Presentational Versus Semantic Styles

There are two schools of thought among front-end developers. Some developers are content to use Foundation’s classes directly in Rails view files. For these developers, the Foundation classes are both practical and descriptive, making it easy for any developer who knows the Foundation framework to visualize the layout of a page.

Other developers take issue with this approach. They argue that Foundation’s markup is often presentational, with class names describing the appearance of the page. In an ideal world, all markup would be semantic, with class names describing the function or purpose of a style. For example, a submit button often needs styling. Compare these two approaches to markup:

  • presentational: <button class="big red button">Order Now</button>
  • semantic: <button class="submit">Order Now</button>

Suppose your user testing indicates a green button generates more sales. With the presentational approach you’d have to change both the Rails view file and the CSS file. With a semantic approach, you’d just change the CSS file to reassign the color of the submit class.

Using Foundation Classes Directly

Foundation often mixes presentational and semantic markup.

For quick and simple websites, where you don’t need to be concerned about long-term maintenance, use Foundation’s CSS classes directly.

For example, you can style a button like this:

  • Foundation 4.0: <button class="large alert button">Order Now</button>

It is is immediately obvious that you’ll get a large button. The alert class is a bit more semantic, indicating it will apply an “alert color” which is red, by default, in Foundation.

Using Sass Mixins with Foundation

If you don’t like the presentational approach, you can use Sass mixins to create your own semantic class names.

Sass mixins add a layer of complexity that can map Foundation class names to your own semantic class names.

For example, the Foundation grid system is presentational. Specifying rows and columns, and quantifying the size of columns, describes the visual appearance of sections of the layout rather than the purpose of each section. The presentational makes it easy visualize the layout of a page. But you’ll be tied to Foundation 4.0 class names for the life of your website. If class names change in Foundation 5.0, or you decide to switch to another front-end framework, it will be difficult to update your application, as you will have to carefully rebuild each view file.

Is it worth the effort to add the complexity of Sass mixins just to future-proof your website? Probably not for a simple website such as the one you are building for Foobar Kadigan.

The rails_layout gem uses Sass mixins to apply CSS style rules to the default application layout. In doing so, the default application layout is free of framework-specific code and can be used with either Twitter Bootstrap or Zurb Foundation.

Before we examine the default application layout, let’s take a look at the Sass mixins supplied by the rails_layout gem.

Look again at the file app/assets/stylesheets/framework_and_overrides.css.scss created by the rails_layout gem:

@ scss
// import the CSS framework
@import “foundation”;

// override for the ‘Home’ navigation link
.top-bar .name {
font-size: 0.8125em;
line-height: 45px; }
.top-bar .name a {
font-weight: bold;
color: white;
padding: 0 15px; }

// THESE ARE EXAMPLES YOU CAN MODIFY
// create mixins using Foundation classes
mixin twelve-columns { @extend .small-12; @extend .columns; } @mixin six-columns-centered { @extend .small-6; @extend .columns; @extend .text-center; } // create your own classes // to make views framework-neutral .column { @include six-columns-centered; } .form { @include grid-column(6); } .form-centered { @include six-columns-centered; } .submit { @extend .button; @extend .radius; } // apply styles to HTML elements // to make views framework-neutral main { @include twelve-columns; background-color: #eee; } section { @extend .row; margin-top: 20px; } @@

The rails_layout gem is in active development so the file you’ve created may be different from the example in this tutorial. It will probably be very similar.

At the top of the file we import the Foundation framework CSS files from the gem.

We override two Foundation style rules so the “Home” navigation link matches the other links in the navigation bar.

Then we use mixins to create semantic classes.

Mixins are declared in Sass files by the @mixin directive, which takes a block of CSS styles, other mixins, or a CSS selector (a CSS class or ID).

If you’d like to combine CSS classes, or rename a CSS class, use the @extend directive to add a CSS class to a mixin.

The first declaration @mixin twelve-columns combines the Foundation classes small-12 and columns to make a new class, twelve-columns.

The second declaration @mixin six-columns-centered makes a column that is six columns wide with centered text.

Next we create a few classes that use the mixins or combine Foundation CSS classes. For example, the new submit class can be used for a rounded button. When we use it in a view, this class will be purely semantic since describes the purpose of the element, allowing us to set its appearance outside of any view file.

Finally, to avoid applying Foundation classes in the application layout file, we apply styles to HTML elements main and section to make the views framework-neutral. We use the @include directive to add the mixins we need. We also use the @extend directive to add a Foundation CSS class. And we directly set CSS properties such as background-color and margin-top.

Using this technique, the file app/assets/stylesheets/framework_and_overrides.css.scss becomes the single point of intersection between the Foundation framework and the application layout. For a simple website, this could be over-engineering and counter-productive. The rails_layout gem uses the technique so that either Twitter Bootstrap or Zurb Foundation can be used without any change to the default application layout.

We’ll use the CSS classes provided by the rails_layout gem in the tutorial application, but if you choose to customize the application, feel free to use Foundation classes directly to keep your project simple.

Application Layout with Zurb Foundation

Let’s look at the application layout file created by the rails_layout gem:

Examine the contents of the file app/views/layouts/application.html.erb:

@ erb
<!DOCTYPE html>



<%= content_for?(:title) ? yield(:title) : “Learn Rails” <span>></span>
= content_for?(:description) ? yield(:description) : “Learn Rails” >">
<
= stylesheet_link_tag “application”, media: “all”, “data-turbolinks-track” => true >
<
# Modernizr is required for Zurb Foundation 4 >
<
= javascript_include_tag “vendor/custom.modernizr” >
<
= javascript_include_tag “application”, “data-turbolinks-track” => true >
<
= csrf_meta_tags %> <%= render ‘layouts/navigation’ %> <%= render ‘layouts/messages’ %> <%= yield %>

@

This file is almost identical to the simple application layout file we looked at in the previous chapter.

Modernizr JavaScript Library

You’ll see the file now includes:

@ erb
.
.
.
<%# Modernizr is required for Zurb Foundation 4 >
<
= javascript_include_tag “vendor/custom.modernizr” %>
.
.
.
@

The Modernizr JavaScript library is a prerequisite for Foundation. Modernizr makes it possible for older browsers to use HTML5 elements. It also detects mobile devices. It must be loaded before Foundation, so it is included above javascript_include_tag "application".

Because we’ve applied Foundation classes to the HTML element main in the app/assets/stylesheets/framework_and_overrides.css.scss file, there’s no need to use Foundation classes directly in the application layout.

Flash Messages with Zurb Foundation

The messages partial we use with Zurb Foundation is complex.

Examine the file app/views/layouts/_messages.html.erb:

@ erb
<%# Rails flash messages styled for Zurb Foundation 4 >
<
flash.each do |name, msg| >
<
if msg.is_a?(String) >
= name == :notice ? “success” : “alert” >">
<
= content_tag :div, msg %>
×

<% end %>

<% end %>
@

We use each to iterate through the flash hash, retrieving a name and msg that are passed to a block to be output as a string. The expression if msg.is_a?(String) serves as a test to make sure we only display messages that are strings. We construct a div that applies Foundation CSS styling around the message. Foundation recognizes a class alert-box and round (for rounded corners). A class of either success or alert styles the message. Rails notice messages will get styled with the Foundation success class. Any other Rails messages, including alert messages, will get styled with the Foundation alert class.

We use the Rails content_tag view helper to create a div containing the message.

Finally, we create a “close” icon by applying the class close to a link. We use the HTML entity &times; (a big “X” character) for the link; it could be the word “close” or anything else we like. Foundation’s integrated JavaScript library will hide the alert box when the “close” link is clicked.

Foundation provides detailed documentation if you want to change the styling of the alert boxes.

Navigation Partial with Zurb Foundation

The layout and styling required for the Foundation navigation bar are in the navigation partial file.

Examine the file app/views/layouts/_navigation.html.erb:

@ erb
<%# navigation styled for Zurb Foundation 4 >



  • <
= link_to ‘Home’, root_path %>
  • Menu
    • <%= render ‘layouts/navigation_links’ %>

    @

    The navigation partial is now more complex, with layout and Foundation classes needed to produce a responsive navigation bar.

    At the conclusion of this chapter, you’ll test the responsive navigation by resizing the window. At small sizes, the navigation links will disappear and be replaced by an icon labeled “Menu.” Clicking the icon will reveal a vertical menu of navigation links. The navigation menu is a great demonstration of the ability of Zurb Foundation to adjust to the small screen size of a tablet or smartphone.

    If you’d like to add a site name or logo to the tutorial application, you can replace the link helper <%= link_to 'Home', root_path %>. It is important to preserve the enclosing layout and classes, even if you don’t want to display a site name or logo. The enclosing layout is used to generate the navigation menu when the browser window shrinks to accommodate a tablet or smartphone.

    You’ll see we wrap the nested partial render 'layouts/navigation_links' with a Foundation class to complete the navigation bar.

    Navigation Links Partial

    The file app/views/layouts/_navigation_links.html.erb is unchanged:

    @ erb
    <%# add navigation links to this file %>
    @

    Later we’ll add links to “About” and “Contact” pages.

    The navigation links partial will be simply a list of navigation links. It doesn’t require additional CSS styling.

    We’re following the separation of concerns principle here. By separating the links from the styling that creates the navigation bar, we segregate the code that is unique to Zurb Foundation. In the future, if the Zurb Foundation layout or CSS classes change, we can make changes without touching the navigation links. If we wish, we can replace the navigation partial and substitute one that uses Twitter Bootstrap styles instead of Foundation, leaving the navigation links intact.

    Set up SimpleForm with Zurb Foundation

    One of the requirements for our tutorial application is a contact form. We could set up styling for the form when we implement the contact page, but it is convenient to set up form styling now, as we would if we were adding multiple forms to the site.

    Rails provides a set of view helpers for forms. They are described in the RailsGuides: Rails Form Helpers document. But, as you’ve learned, Rails has more than one stack, and most developers use an alternative set of form helpers named SimpleForm, provided by the SimpleForm gem. The SimpleForm helpers are more powerful, easier to use, and offer an option for styling with Zurb Foundation.

    In your Gemfile, you’ve already added:

    @ ruby
    gem ‘simple_form’
    @

    and previously run $ bundle install.

    Run the generator to install SimpleForm with a Zurb Foundation option:

    @ console
    $ rails generate simple_form:install —foundation
    @

    which installs several configuration files:

    @ console
    config/initializers/simple_form.rb
    config/initializers/simple_form_foundation.rb
    config/locales/simple_form.en.yml
    lib/templates/erb/scaffold/_form.html.erb
    @

    Here the SimpleForm gem uses the rails generate command to create files for initialization and localization (language translation). SimpleForm can be customized with settings in the initialization file. We’ll use the defaults.

    Clone this wiki locally