搭建开发rails环境

来源:互联网 发布:codol账号数据异常 编辑:程序博客网 时间:2024/04/30 03:25
rvm use 1.9.3-p125

rvm gemset create rails323_r193_xmcrm

rvm use 1.9.3-p125@rails323_r193_xmcrm

gem install rails -v 3.2.3

rails new xmcrm

cd xmcrm

修改gemfile

source 'https://rubygems.org'
 
gem 'rails', '3.2.3'
 
# Bundle edge Rails instead:
# gem 'rails', :git => 'git://github.com/rails/rails.git'
 
#gem 'sqlite3'
gem 'mysql2'
 
gem 'json'
 
gem 'dynamic_form'
 
gem 'execjs'
 
gem 'therubyracer'
 
gem 'devise'
 
gem "will_paginate"
 
gem 'acts-as-taggable-on', '~> 2.2.2'
 
# Gems used only for assets and not required
# in production environments by default.
group :assets do
  gem 'sass-rails',   '~> 3.2.3'
  gem 'coffee-rails', '~> 3.2.1'
 
  # See https://github.com/sstephenson/execjs#readme for more supported runtimes
  # gem 'therubyracer', :platform => :ruby
 
  gem 'uglifier', '>= 1.0.3'
end
 
gem 'jquery-rails'
 
group :test, :development do
  gem "rspec-rails", "~> 2.8.1"
end
 
group :test do
  gem 'cucumber-rails'
  gem 'capybara'
  gem 'database_cleaner'
  gem 'turn', :require => false
  gem "factory_girl_rails"
  gem "minitest"
end
 
# To use ActiveModel has_secure_password
# gem 'bcrypt-ruby', '~> 3.0.0'
 
# To use Jbuilder templates for JSON
# gem 'jbuilder'
 
# Use unicorn as the app server
# gem 'unicorn'
 
# Deploy with Capistrano
group :development do
  gem 'capistrano'
end
 
# To use debugger
# gem 'ruby-debug19', :require => 'ruby-debug'

bundle install

修改database.yml

development:
    adapter: mysql2
    database: xmcrm_development
    pool: 5
    timeout: 5000
    encoding: utf8
    reconnect: false
    username: root
    password: 1q2w3e4r
    host: localhost
 
test: &test
    adapter: mysql2
    database: xmacrm_test
    pool: 5
    timeout: 5000
    encoding: utf8
    reconnect: false
    username: root
    password: 1q2w3e4r
    host: localhost
 
production:
    adapter: mysql2
    database: xmcrm_production
    pool: 5
    timeout: 5000
    encoding: utf8
    reconnect: false
    username: root
    password: 1q2w3e4r
    host: localhost

rake db:create

rails generate devise:install

1. Ensure you have defined default url options in your environments files. Here
   is an example of default_url_options appropriate for a development environment
   in config/environments/development.rb:
 
     config.action_mailer.default_url_options = { :host => 'localhost:3000' }
 
   In production, :host should be set to the actual host of your application.
 
2. Ensure you have defined root_url to *something* in your config/routes.rb.
   For example:
 
     root :to => "home#index"
 
3. Ensure you have flash messages in app/views/layouts/application.html.erb.
   For example:
 
     <p class="notice"><%= notice %></p>
     <p class="alert"><%= alert %></p>


把locales里增加devise.cn.yml内容如下

# encoding: utf-8  
cn:
  errors:
    messages:
      expired: "已经过期,请重新获取"
      not_found: "不存在"
      already_confirmed: "已经通过验证,请直接登录"
      not_locked: "没有锁定"
      not_saved:
        one: "发生了一个错误在%{resource} 保存的时候:"
        other: "%{count}个错误禁止了%{resource}的保存:"
 
  devise:
    failure:
      already_authenticated: '您已经登录.'
      unauthenticated: '您在进行下一步操作之前必须登录或者注册.'
      unconfirmed: '您在进行下一步操作之前必须验证您的邮箱.'
      locked: '您的账号已经被锁定.'
      invalid: '邮件或者密码错误.'
      invalid_token: 'authentication token 非法.'
      timeout: '您的登录时间已经过期,在下一步操作之前请重新登录.'
      inactive: '您的账号还没有被激活.'
    sessions:
      signed_in: '登录成功.'
      signed_out: '注销成功.'
    passwords:
      send_instructions: '您将会在几分钟内收到一封关于如何重置密码的邮件.'
      updated: '您的密码已经重置成功,您现在已经登录.'
      updated_not_active: '您的密码已经成功更换.'
      send_paranoid_instructions: "如果您的邮箱存在我们服务器的数据库中,您将受到一封恢复密码的邮件在您的注册邮箱中."
    confirmations:
      send_instructions: '您将在几分钟内收到一封邮件关于如何验证您的注册邮箱.'
      send_paranoid_instructions: '如果您的邮箱存在我们服务器的数据库中,您将受到一封如何验证账户的邮件在您的注册邮箱中.'
      confirmed: '您的账户已经成功验证,您已经登录了网站.'
    registrations:
      signed_up: '欢迎您!您已经成功注册.'
      signed_up_but_unconfirmed: '一个含有验证信息的链接已经发送到了您的邮箱地址,请打开此邮件来激活您的账户.'
      signed_up_but_inactive: '您已经成功注册,但是由于您的邮箱还没有得到验证,所以暂时还不能让您登录.'
      signed_up_but_locked: '您已经成功注册. 但是由于您的账户已经被锁定,所以暂时不能让您登录.'
      updated: '您已经成功更新了您的账户信息.'
      update_needs_confirmation: "您已经成功更新了您的账户信息, 但是我们没有验证您的新的邮件地址. 请登录您的邮箱并点击验证的链接来完成此次邮箱地址的修改."
      destroyed: '再见!您的账户已经成功消除,希望能很快再次见到您.'
    unlocks:
      send_instructions: '您的注册邮箱地址将在几分钟内收到一封邮件关于如何解除账户锁定.'
      unlocked: '您的账户已经成功解除锁定.请登录以继续下一步操作.'
      send_paranoid_instructions: '如果您的账户存在,您的邮箱在几分钟内将收到一份邮件关于如何解除账户锁定.'
    omniauth_callbacks:
      success: '成功完成从 %{kind} 的账户认证.'
      failure: '不能完成从 %{kind} 的认证,因为 "%{reason}".'
    mailer:
      confirmation_instructions:
        subject: '请激活您的邮箱'
      reset_password_instructions:
        subject: '重新设定您的密码'
      unlock_instructions:
        subject: '解除账户锁定'


application.rb的修改

config.time_zone = 'Beijing'
config.i18n.default_locale = :cn
config.encoding = "utf-8"
config.assets.enabled = false
config.filter_parameters += [:password, :password_confirmation]

创建用户modelrails generate devise Userrails generate devise:viewsrails generate devise:views users

修改user的model为

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :token_authenticatable, :confirmable,
  # :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable,
         :token_authenticatable, :confirmable, :lockable, :timeoutable
 
  # Setup accessible (or protected) attributes for your model
  attr_accessible :username, :email, :password, :password_confirmation, :remember_me
  # attr_accessible :title, :body
end


修改user的migrate为

class DeviseCreateUsers < ActiveRecord::Migration
  def change
    create_table(:users) do |t|
      ## Database authenticatable
      t.string :username, :null => false, :default => ""
      t.string :email,              :null => false, :default => ""
      t.string :encrypted_password, :null => false, :default => ""
 
      ## Recoverable
      t.string   :reset_password_token
      t.datetime :reset_password_sent_at
 
      ## Rememberable
      t.datetime :remember_created_at
 
      ## Trackable
      t.integer  :sign_in_count, :default => 0
      t.datetime :current_sign_in_at
      t.datetime :last_sign_in_at
      t.string   :current_sign_in_ip
      t.string   :last_sign_in_ip
 
      ## Confirmable
      t.string   :confirmation_token
      t.datetime :confirmed_at
      t.datetime :confirmation_sent_at
      t.string   :unconfirmed_email # Only if using reconfirmable
 
      ## Lockable
      t.integer  :failed_attempts, :default => 0 # Only if lock strategy is :failed_attempts
      t.string   :unlock_token # Only if unlock strategy is :email or :both
      t.datetime :locked_at
 
      ## Token authenticatable
      t.string :authentication_token
 
 
      t.timestamps
    end
 
    add_index :users, :email,                :unique => true
    add_index :users, :reset_password_token, :unique => true
    add_index :users, :confirmation_token,   :unique => true
    add_index :users, :unlock_token,         :unique => true
    add_index :users, :authentication_token, :unique => true
  end
end

在routes加上

root :to => "home#index" devise_for :users

修改config/initializers/devise.rbconfig.confirmation_keys = [ :email ]config.remember_for = 2.weeksconfig.mailer_sender = "noreply@xxx.com"config.encryptor = :sha512config.allow_unconfirmed_access_for = 0.days # 这个用来严格要求必须是验证过邮箱的

修改development.rb

config.host_url = "http://localhost:3000/"
config.staticfile_server_url = "http://localhost:3000/"
 
 
config.action_mailer.default_url_options = { :host => 'localhost:3000' }
config.action_mailer.delivery_method = :smtp
 
config.action_mailer.smtp_settings = {
  :address              => "smtp.qq.com",
  :port                 => 25,
  :domain               => 'www.xxx.com',
  :user_name            => 'noreply@xxx.com',
  :password             => '1837d1ahdkr',
  :authentication       => 'plain',
  :enable_starttls_auto => true  }


修改production.rb

config.host_url = "http://crm.xxx.com/"
config.staticfile_server_url = "http://crm.xxx.com/"
 
config.action_mailer.default_url_options = { :host => 'crm.xxx.com' }
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
  :address              => "smtp.qq.com",
  :port                 => 25,
  :domain               => 'www.xxx.com',
  :user_name            => 'noreply@xxx.com',
  :password             => 'ashdauisdqib',
  :authentication       => 'plain',
  :enable_starttls_auto => true  }


重写注册组建routes添加

用户系统devise 重写了注册组件
devise_for :users, :controllers => {:registrations => "registrations"}
 
devise_scope :user do
  # 等待邮箱验证
  match "awaiting_confirmation", :to => "registrations#awaiting_confirmation", :via => [:get], :as => "awaiting_confirmation"
  # 微博用户授权以后如果没有注册就会来这个地址注册
  # match "users/weibo_sign_up", :to => "registrations#weibo_new", :via => [:get], :as => "new_weibo_user_registration"      
end


添加registrations_controller.rb

# encoding: utf-8
class RegistrationsController < Devise::RegistrationsController
  # 微博注册界面
  # def weibo_new
  #     resource = build_resource({})
  #     if session[:weibo_name]
  #       resource.name = session[:weibo_name]
  #     end    
  #     respond_with resource
  #   end
   
  # 重写创建方法
  def create
    # 如果session里有 weibo_uid 且 Weibouser 没有此纪录 则创建一个Weibouser
    build_resource
    if resource.save
      # weibo用户 start  
      # if session[:weibo_uid]
      #         weibouser = Weibouser.find_by_wuid(session[:weibo_uid])
      #         if not weibouser
      #           weibouser = Weibouser.new
      #           weibouser.user = resource
      #           weibouser.wuid = session[:weibo_uid]
      #           weibouser.save
      #         end       
      #       end
      # weibo用户 end
      if resource.active_for_authentication?
        set_flash_message :notice, :signed_up if is_navigational_format?
        sign_in(resource_name, resource)           
        respond_with resource, :location => after_sign_up_path_for(resource)
      else
        set_flash_message :notice, :"signed_up_but_#{resource.inactive_message}" if is_navigational_format?
        expire_session_data_after_sign_in!
        respond_with resource, :location => after_inactive_sign_up_path_for(resource)
      end
    else
      clean_up_passwords resource
      respond_with resource
    end
  end
  # 提示去验证邮箱
  def awaiting_confirmation
    @email = params[:email]
    render :template => 'devise/registrations/awaiting_confirmation'
  end
   
  protected
  # 重写登录非法的返回
  def after_inactive_sign_up_path_for(resource)
    #respond_to?(:root_path) ? root_path : "/"
    "/awaiting_confirmation?email=#{resource.email}"  
  end
end


添加devise/registrations/awaiting_confirmation 的view

恭喜!您已经成功注册crm.xxx.com
<br>
去验证您的邮箱,<%= @email%>
<br>
如果您已经验证完毕 <%= link_to "回首页", root_path %>


在application.html.erb里添加提示信息

<!-- devise的提示信息 start -->
 
    <% if flash[:notice] %>
    <p class="notice"><%= notice %></p>
    <% end %>
    <% if flash[:alert] %>
    <p class="alert"><%= alert %></p>
    <% end %>
    <% if flash[:error] %>
    <p class="error"><%= flash[:error] %></p>
    <% end %>
    <% if flash[:success] %>
    <p class="success"><%= flash[:success] %></p>
    <% end %>
<!-- devise的提示信息 end -->


在注册和编辑的view里加上usernameviews/devise/registrations/new.html.erb 和edit.html.erb

<div><%= f.label :username %><br>
  <%= f.text_field :username %></div>


application.html.erb里面添加

<script type="text/javascript" src="%3C%=%20Xmcrm::Application.config.staticfile_server_url%20%%3Ejquery/jquery_1.7.1.min.js"></script>
  <script type="text/javascript" src="%3C%=%20Xmcrm::Application.config.staticfile_server_url%20%%3Ejquery/jquery-ui-1.8.18.custom.min.js"></script>
  <script type="text/javascript" src="%3C%=%20Xmcrm::Application.config.staticfile_server_url%20%%3Ejquery_ujs.js"></script>
  <script type="text/javascript" src="%3C%=%20Xmcrm::Application.config.staticfile_server_url%20%%3Ejquery/jquery.ui.datepicker-zh-CN.js"></script>
  <script type="text/javascript" src="%3C%=%20Xmcrm::Application.config.staticfile_server_url%20%%3Ejquery/jquery-ui-timepicker-addon.js"></script>
  <script type="text/javascript" src="%3C%=%20Xmcrm::Application.config.staticfile_server_url%20%%3Ejquery/jquery.relatedselects.min.js"></script>
  <script type="text/javascript" src="%3C%=%20Xmcrm::Application.config.staticfile_server_url%20%%3Ejquery/fullcalendar/fullcalendar.min.js"></script>
  <script src="%3C%=%20Xmcrm::Application.config.staticfile_server_url%20%%3Ejquery/validation/languages/jquery.validationEngine-zh_CN.js" type="text/javascript" charset="utf-8"></script>
  <script src="%3C%=%20Xmcrm::Application.config.staticfile_server_url%20%%3Ejquery/validation/jquery.validationEngine.js" type="text/javascript" charset="utf-8"></script>
  <link rel="stylesheet" href="<%= Xmcrm::Application.config.staticfile_server_url %>jquery/south-street/jquery-ui-1.8.18.custom.css" type="text/css"/>
  <link rel="stylesheet" href="<%= Xmcrm::Application.config.staticfile_server_url %>style.css" type="text/css"/>
  <link rel="stylesheet" href="<%= Xmcrm::Application.config.staticfile_server_url %>jquery/fullcalendar/fullcalendar.css" type="text/css"/>
  <link rel="stylesheet" href="<%= Xmcrm::Application.config.staticfile_server_url %>jquery/validation/validationEngine.jquery.css" type="text/css"/>
  <link rel="stylesheet" href="<%= Xmcrm::Application.config.staticfile_server_url %>jquery/fullcalendar/fullcalendar.print.css" type="text/css" media='print'/>
  <link rel="stylesheet" href="<%= Xmcrm::Application.config.staticfile_server_url %>jquery/fullcalendar/cupertino/theme.css" type="text/css" media='print'/>
  <%= csrf_meta_tags %>

然后把相应的文件拷贝进去

远程服务器git初始化
mkdir -p /opt/git/xmcrm.git
cd /opt/git/xmcrm.git/
git --bare init
chown -R xx.nobody /opt/git/
/etc/init.d/git-daemonstart

客户端的初始化和提交

git init
git add ./
git commit -m "first commit"
git remote add originssh://xx@xsudo.com:22229/opt/git/xmcrm.git
git push -u origin master


部署服务器的rvm环境配置
rvm use 1.9.3-p125
 
rvm gemset create rails323_r193_xmcrm
 
rvm use 1.9.3-p125@rails323_r193_xmcrm
 
gem installrails -v 3.2.3

添加capistrano支持

capify ./

然后修改deploy.rb

为以下内容

$:.unshift(File.expand_path('./lib', ENV['rvm_path']))
require 'rvm/capistrano'
require 'bundler/capistrano'
 
set :rails_env, 'production'
set :rvm_type, :system
set :rvm_ruby_string, '1.9.3-p125@rails323_r193_xmcrm'
set :rvm_path, '/usr/local/rvm/'
set :rvm_bin_path, "#{rvm_path}/bin"
set :rvm_lib_path, "#{rvm_path}/lib"
set :deploy_via, :remote_cache
 
set :normalize_asset_timestamps, false
# set :default_environment, {
#   'PATH'                    => "#{rvm_path}/gems/ruby/1.9.1/bin:#{rvm_bin_path}/bin:$PATH",
#   'RUBY_VERSION'    => '1.9.2',
#   'GEM_HOME'        => "#{rvm_path}/gems/#{rvm_ruby_string}",
#   'GEM_PATH'        => "#{rvm_path}/gems/#{rvm_ruby_string}",
#   'BUNDLE_PATH'     => "#{rvm_path}/gems/#{rvm_ruby_string}"
# }
 
set :application, "crm.xxx.com"
set :repository,  "ssh://xx@xsudo.com:22229/opt/git/xmcrm.git"
 
set :scm, :git
# Or: `accurev`, `bzr`, `cvs`, `darcs`, `git`, `mercurial`, `perforce`, `subversion` or `none`
 
 
role :web, "crm.xxx.com"                          # Your HTTP server, Apache/etc
role :app, "crm.xxx.com"                          # This may be the same as your `Web` server
role :db,  "crm.xxx.com", :primary => true # This is where Rails migrations will run
#role :db,  "your slave db-server here"
set :port, 22229
set :use_sudo, true
set :user, "xx"    # 上传了ssh的public key
set :web_user, "nobody"
#set :password, "passwd"
default_run_options[:pty] = true
 
 
set :branch, "master"
set :deploy_to, "/home/xx/crm/xxx.com/htdocs/#{application}"
 
 
set :keep_releases, 5
 
# 这些是为了替换一些正式环境的配置
task :symlink_database_yml do
  run "rm #{release_path}/config/database.yml"
  run "ln -sfn #{shared_path}/config/database.yml #{release_path}/config/database.yml"
  run "ln -sfn #{shared_path}/config/environments/production.rb #{release_path}/config/environments/production.rb"
end
 
after "bundle:install", "symlink_database_yml"
after "deploy:symlink", "custom:set_permissions_for_runtime"
 
namespace :deploy do
  task :start, :roles => :web, :except => { :no_release => true } do
    run "#{try_sudo} cd /root/scripts && #{try_sudo} ./crm.xxx.com.sh start"
    run "cd /etc/init.d && #{try_sudo} ./nginx start"
  end
  task :stop, :roles => :web, :except => { :no_release => true } do
    run "#{try_sudo} cd /root/scripts && #{try_sudo} ./crm.xxx.com.sh stop"
    run "/etc/init.d && #{try_sudo} ./nginx stop"
  end
  task :restart, :roles => :web, :except => { :no_release => true } do
    run "#{try_sudo} cd /root/scripts && #{try_sudo} ./crm.xxx.com.sh restart"
    run "cd /etc/init.d && #{try_sudo} ./nginx restart"
  end
end
 
namespace :custom do
  task :set_permissions_for_runtime, :except => { :no_release => true } do
    #chown of files to current user
    #sudo "chown -R #{web_user}:#{web_user} #{deploy_to}"
    run "#{try_sudo} chown -R #{web_user}.#{web_user} #{latest_release}"
    run "#{try_sudo} chown -R #{web_user}.#{web_user} #{shared_path}/log"
    run "#{try_sudo} chown -R #{web_user}.#{web_user} #{shared_path}/pids"
    run "#{try_sudo} chmod -R 0666 #{shared_path}/log/production.log"
  end
end
 
# 常用的任务
# $ cap deploy:setup
# $ cap deploy
# $ cap deploy:migrate
# $ cap deploy:migrations



原创粉丝点击