Taylor Huston Taylor Huston - 1 year ago 126
CSS Question

Rails - Difference between @import and *= require?

So I've got a relatively simple Rails app, and I wanted to add some material design styling to it through Bootstrap.

I've added the following gems to my Gemfile:

gem 'bootstrap-sass'
gem 'bootstrap-material-design'

Now they both work, my question is to why I seem to have to add them to my app in different ways. For vanilla Boostrap I just import it into the view specific (I think that's the right term) scss file like normal.

@import "bootstrap-sprockets";
@import "bootstrap";

But for the Material Design gem I have to 'require' it to the root application.css file instead

*= require bootstrap-material-design

Why the difference, and what is that require syntax actually doing?

Answer Source

The include and require methods do very different things.

The require method does what include does in most other programming languages: run another file. It also tracks what you've required in the past and won't require the same file twice. To run another file without this added functionality, you can use the load method.

The include method takes all the methods from another module and includes them into the current module. This is a language-level thing as opposed to a file-level thing as with require. The include method is the primary way to "extend" classes with other modules (usually referred to as mix-ins). For example, if your class defines the method "each", you can include the mixin module Enumerable and it can act as a collection. This can be confusing as the include verb is used very differently in other languages.

So if you just want to use a module, rather than extend it or do a mix-in, then you'll want to use require.

Oddly enough, Ruby's require is analogous to C's include, while Ruby's include is almost nothing like C's include.

More info

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download