Rails Stack - MongoDB, Bootstrap

Rails Stack - MongoDB

Introduction

This is an introduction of creating rails stack together with MongoDB.
The tech stack includes:

  • Rails
  • MongoDB
  • Bootstrap
  • AngularJS
  • Bower
  • Capistrano
  • Nginx
  • RSpec

Create a rails application

It seems that TurboLinks does not play well with AngularJS. So we will not enable TurboLinks when we create the rails application.
Since we will use RSpec, here we skip the test-unit too (-T).

rails new -T --skip-turbolinks rails-stack-mongo

You might want to add config/secrets.yml and config/database.yml into .gitignore to avoid expose them.

If you've already checked in those two files and want to remove them. Try the following:

git rm config/secrets.yml config/database.yml

Setup Bower

We will use bower to manage the front-end libraries, including bootstrap. So here we need to setup bower first.

Install Bower

OS X:

sudo npm install -g bower

Ubuntu:

sudo apt-get update
sudo apt-get install nodejs npm
sudo npm install -g bower
sudo ln -s /usr/bin/nodejs /usr/bin/node

In case the git:// protocol is not working in your network, you can let git to replace git:// with https://.

git config --global url."https://".insteadOf git://

Use Bower in Rails

We will use bower-rails to mange bower related actions. The main reason we use this gem instead of using bower directly is that, this gem provides a helper task rake bower:resolve to deal with the assets path problem in rails. For example in rails, we might found that the Glyphicons work well in development, but will raise 404 - not found on production. By using bower-rails gem, we can handle such situation easily.

To use this gem, we need to add it into our Gemfile.

gem 'bower-rails', '~> 0.9.2'

Run bundle install.
Then run

rails g bower_rails:initialize

This will add Bowerfile and initializers/bower_rails.rb.

The Bowerfile is just like a Gemfile, but for bower. It uses an DSL developed to provide similar feel like using bundler.

You might also want to modify you .gitignore to exclude the libraries managed by bower from your source control.
Here is a sample .gitignore

# See https://help.github.com/articles/ignoring-files for more about ignoring files.
#
# If you find yourself ignoring temporary files generated by your text editor
# or operating system, you probably want to add a global ignore instead:
#   git config --global core.excludesfile '~/.gitignore_global'

# Ignore bundler config.
/.bundle

# Ignore the default SQLite database.
/db/*.sqlite3
/db/*.sqlite3-journal

# Ignore all logfiles and tempfiles.
/log/*
!/log/.keep
/tmp

### Rails template
*.rbc
capybara-*.html
.rspec
/log
/tmp
/db/*.sqlite3
/db/*.sqlite3-journal
/public/system
/coverage/
/spec/tmp
**.orig
rerun.txt
pickle-email-*.html

# TODO Comment out these rules if you are OK with secrets being uploaded to the repo
config/initializers/secret_token.rb
config/secrets.yml

## Environment normalisation:
/.bundle
/vendor/bundle

# these should all be checked in to normalise the environment:
# Gemfile.lock, .ruby-version, .ruby-gemset

# unless supporting rvm < 1.11.0 or doing something fancy, ignore this:
.rvmrc

# if using bower-rails ignore default bower_components path bower.json files
/vendor/assets/bower_components
*.bowerrc
bower.json


### SVN template
.svn/


### Windows template
# Windows image file caches
Thumbs.db
ehthumbs.db

# Folder config file
Desktop.ini

# Recycle Bin used on file shares
$RECYCLE.BIN/

# Windows Installer files
*.cab
*.msi
*.msm
*.msp

# Windows shortcuts
*.lnk


### JetBrains template
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm

*.iml

## Directory-based project format:
.idea/
# if you remove the above rule, at least ignore the following:

# User-specific stuff:
# .idea/workspace.xml
# .idea/tasks.xml
# .idea/dictionaries

# Sensitive or high-churn files:
# .idea/dataSources.ids
# .idea/dataSources.xml
# .idea/sqlDataSources.xml
# .idea/dynamic.xml
# .idea/uiDesigner.xml

# Gradle:
# .idea/gradle.xml
# .idea/libraries

# Mongo Explorer plugin:
# .idea/mongoSettings.xml

## File-based project format:
*.ipr
*.iws

## Plugin-specific files:

# IntelliJ
out/

# mpeltonen/sbt-idea plugin
.idea_modules/

# JIRA plugin
atlassian-ide-plugin.xml

# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties


### OSX template
.DS_Store
.AppleDouble
.LSOverride

# Icon must end with two \r
Icon

# Thumbnails
._*

# Files that might appear on external disk
.Spotlight-V100
.Trashes

# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk

Use Bootstrap

Install Bootstrap via Bower

Edit Bowerfile, add

asset 'bootstrap'

Then run

rake bower:install

to install bootstrap.

Use Bootstrap in rails

Edit config/application.rb to add bower_components into asset pipeline.

config.assets.paths << Rails.root.join('vendor', 'assets', 'bower_components')
# config.assets.paths << Rails.root.join('vendor', 'assets', 'bower_components', 'bootstrap', 'dist', 'fonts')
config.assets.precompile << %r(.*.(?:eot|svg|ttf|woff|woff2)$)

Edit app/assets/javascripts/application.js

//= require bootstrap/dist/js/bootstrap

Edit app/assets/stylesheets/application.css

*= require bootstrap/dist/css/bootstrap

Fix bootstrap fonts missing issue

Edit config/initializers/bower_rails.rb, set bower_rails.resolve_before_precompile = true. This will run rake bower:resolve before compile. It will replace the url() in the css with <%= asset_path() %> helper.

Verify that Bootstrap works in Development

First we need to add a verification page.

rails g controller page index

Edit apps/views/page/index.html.erb

<button type="button" class="btn btn-default" aria-label="Left Align">
  <span class="glyphicon glyphicon-align-left" aria-hidden="true"></span>
</button>

<button type="button" class="btn btn-default btn-lg">
  <span class="glyphicon glyphicon-star" aria-hidden="true"></span> Star
</button>

<!-- Single button -->
<div class="btn-group">
  <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
    Action <span class="caret"></span>
  </button>
  <ul class="dropdown-menu" role="menu">
    <li><a href="#">Action</a></li>
    <li><a href="#">Another action</a></li>
    <li><a href="#">Something else here</a></li>
    <li class="divider"></li>
    <li><a href="#">Separated link</a></li>
  </ul>
</div>

<!-- Standard button -->
<button type="button" class="btn btn-default">Default</button>

<!-- Provides extra visual weight and identifies the primary action in a set of buttons -->
<button type="button" class="btn btn-primary">Primary</button>

<!-- Indicates a successful or positive action -->
<button type="button" class="btn btn-success">Success</button>

<!-- Contextual button for informational alert messages -->
<button type="button" class="btn btn-info">Info</button>

<!-- Indicates caution should be taken with this action -->
<button type="button" class="btn btn-warning">Warning</button>

<!-- Indicates a dangerous or potentially negative action -->
<button type="button" class="btn btn-danger">Danger</button>

<!-- Deemphasize a button by making it look like a link while maintaining button behavior -->
<button type="button" class="btn btn-link">Link</button>

Start rails in development mode:

rails s

Access http://localhost:3000/page/index to make sure that Bootstrap works well in development mode.

Verify Bootstrap works in production mode

Edit config/secrets.yml to generate secret_key_base which is required to start WEBrick in produciton mode.

rake secret

Precompile assets from production

RAILS_ENV=production rake assets:clobber
RAILS_ENV=production rake assets:clean
RAILS_ENV=production rake assets:precompile

Start WEBrick in production mode

RAILS_SERVE_STATIC_FILES=true rails s -e production

Note: RAILS_SERVE_STATIC_FILES=true is added here because by default static files like *.css will not beserved by WEBrick in produciton mode. Check config.serve_static_files in config/environments/production.rb for more details.

Access http://localhost:3000/page/index to make sure that Bootstrap works well in production mode.

Use MongoDB

Use Mongoid as ORM driver. Edit Gemfile,

gem 'mongoid', '~> 4.0.0'

Then run bundle install.

Create mongoid.yml.

rails g mongoid:config

Create Controller

rails g scaffold Task name:string description:text status:string

Restart your WEBrick server.

Setup to use Bootstrap theme

Checkout Bootstrap's sample to setup the basic theme.

Edit app/views/layouts/application.html.erb,

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="description" content="">
  <meta name="author" content="">
  <title>Rivendell</title>
  <%= stylesheet_link_tag 'application', media: 'all' %>
  <%= csrf_meta_tags %>
</head>
<body>
<div class="container">
  <nav class="navbar navbar-default">
    <div class="navbar-header">
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <a class="navbar-brand" href="#">Rivendell</a>
    </div>
    <div id="navbar" class="collapse navbar-collapse">
      <ul class="nav navbar-nav">
        <li class="active"><%= link_to('Home', root_path) %></li>
        <li><%= link_to('Tasks', tasks_path) %></li>
      </ul>
    </div>
    <!--/.nav-collapse -->
  </nav>
  <%= yield %>
</div>

<!-- /.container -->
<%= javascript_include_tag 'application' %>
</body>
</html>

Note: <%= javascript_include_tag 'application' %> is put at the bottom to speed up the page loading.

推荐阅读更多精彩内容

  • 兰花不好养,许多花友都是屡败屡战,尤其是烂根,养兰最怕遇到这个。别怕,赶紧偷学兰花达人这3个小妙招,让您的保持青绿...
    南国小花匠阅读 139评论 0 0
  • 在听墨雪讲完后,大家都表情茫然了!这世上怎么会有“长生药”这一定是糊弄人的。但随后,只见爷爷表情复杂,在吸吐着...
    Pan龙腾阅读 45评论 0 0
  • 今天说好的电话面试,但是已经过去说好的时间点半个多小时了,期间我一度以为自己手机停机,让别人打电话给我,还发短信查...
    来不及对你说的话阅读 79评论 0 0
  • 这次回来,吃了很多顿饭,见了很多的人,哪怕有些人只是匆匆一面... 每次回来,感慨很多。 还好有你们 ,让我对这个...
    倾城遗忘阅读 57评论 0 0