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.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,937评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,503评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,712评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,668评论 1 276
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,677评论 5 366
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,601评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,975评论 3 396
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,637评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,881评论 1 298
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,621评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,710评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,387评论 4 319
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,971评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,947评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,189评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 44,805评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,449评论 2 342

推荐阅读更多精彩内容