Tag: rails

Deploy Rails appliction to sub-uri

Sometimes you may want to deploy a Rails application to sub-uri. But it's not seamless if you didn't write your code carefully. The main problem is absolute url.

Avoid absolute url

By default, Rails application only work under root uri unless properly configured. And (maybe) most developers are supposing that the application will be deployed under root uri when writing code. So absolute url is widely used, and they break when deployed under sub-uri. So we should avoid using absolute url. Use relative url or url helpers instead. The are two types of url in Rails: asset url and route url.

Asset url

Since most Rails applications are using Rails Asset Pipeline to manage assets, asset urls are usually generated by asset url helpers like asset_path, asset_url, image_path, etc. These helpers will take care of sub-uri for you if you have configured properly. (See AssetUrlHelper for more helpers and their usage. These helpers are available in view layer. To use them in other places, prefix them with ActionController::Base.helpers.) However, if you put assets directly under public folder, then it's your own responsibility to take care of sub-uri. In such case, use relative url or prefix with Rails.configuration.relative_url_root.

Asset Pipeline

You must set RAILS_RELATIVE_URL_ROOT environment variable when precompiling assets, otherwise url generated by url helpers (such as image-url in scss) would not include sub-uri.

RAILS_RELATIVE_URL_ROOT=/sub-uri bundle exec rake assets:precompile

If you use some deployer (such as mina, capistrano) to automatically precompile assets in production environments, then you should refer to the deployer's documentation about how to pass environment variables to precompiling task. For mina 0.3.x, you can set env_vars in your deploy.rb:

set :env_vars, 'RAILS_RELATIVE_URL_ROOT=/sub-uri'
Read more >>

使用Capistrano部署Rails应用

Capistrano是一个远程服务器自动化工具,使用Ruby编写。 它是一个通用类型的工具,并非专为Rails设计,但对Rails支持很好。

优点

  • 无需对服务器进行任何配置
  • 一键部署、回滚
  • 易于扩展,可方便地添加自定义任务

基本原理

预先定义一系列任务(本质上都是shell脚本),然后通过ssh在远程服务器上执行任务。 使用钩子定义任务的执行时间、顺序。 可创建多套部署方案,capistrano中称为stage,每个stage有一个单独的配置文件。

基本流程

假定服务器上使用Nginx + Passenger + Rvm运行Rails应用,具体安装配置参见各软件文档。 部署Rails应用的基本流程是:

  1. 将代码推送到远程仓库
  2. 本地执行capistrano部署命令
  3. capistrano通过ssh连接远程服务器,从远程代码仓库拉取代码,然后执行安装依赖、编译资源文件、迁移数据库等任务
  4. 重启passenger使新代码生效

基本要求

服务器

Read more >>