rails筆記(ruby web框架)
阿新 • • 發佈:2018-12-29
一、新建rails專案步驟:
1.生成新專案
rails new demo
cd demo vi Gemfile 末尾end前增加 gem 'execjs' gem 'therubyracer' 2.測試服務是否可用 rails s -b 0.0.0.0 http://localhost:3000/ 3.配置root頁面(可忽略) root to: redirect('/ccconsole/chart') 4.配置資料庫(可忽略)
vi config/database.yml
(1)sqlite3(預設)
development:
adapter: sqlite3
database: db/development.sqlite3
pool: 5
timeout: 5000
(2)postgresql
development:
adapter: postgresql
host: 9.186.88.100
database: ccdb
port: 5432
username: postgres
password: xx
encoding: utf8
二、rails生成空資料庫 (1)建立資料庫(只需執行一次,可忽略) rake db:create
(2)建立執行的migrate 表文件
rails g scaffold book name:string
注意:
1.都是小寫。
2.如果你資料庫建立了book這張表,他會報錯。
3.scffold生成表,表名會變成複數。
4.會自動生成id、created_at、updated_at欄位。
5.常用有的型別 integer string float boolean decimal text
ruby是弱型別語言,對變數的定義不是很嚴格。
(3)制動 在資料庫建立表
rake db:migrate RAILS_ENV=development
其他:
/config/routes.rb這個檔案可配置路由。
3.
生成model、controller、view
rails g scaffold book name price:integer
rake db:migrate RAILS_ENV=development
用migrate方式修改資料:
新建20170320141610_update_techspec_mapping.rb
class UpdateTechspecMapping < ActiveRecord::Migration
def change
TechspecMapping.where(欄位: '修改前的值').update_all(欄位: '修改後的值')
end
end
執行: rake db:migrate VERSION=20120613163818
回退: rake db:migrate:down VERSION=20120613163730
回退rails g scaffold 命令 rails destroy scaffold 表名
看rails路徑命令 rake routes
rails命令:
(1)生成model相關檔案
rails g scaffold compliancerun starttime:timestamp node server_num:integer
(2)修改model
rails g migration add_column_to_updatedresources cookbook:string
rake db:seed 報錯
bundle exec rake db:migrate
bundle update
三、配置404,500等頁面
vi config/routes.rb
get '500', :to => 'custom_errors#server_error'
get '502', :to => 'custom_errors#server_error'
get '504', :to => 'custom_errors#server_error'
get '422', :to => 'custom_errors#server_error'
get '404', :to => 'custom_errors#rescue404'
四、rails專案目錄結構(程式自動生成) 1.app資料夾(rails的核心部分,也可以說存放的是針對專案的所有程式碼) 包括6個子資料夾 assets 圖片、js和樣式表 controllers 驅動業務邏輯的控制器 helpers 檢視輔助類,一些常用的程式碼段 mailers 與郵件服務相關的類 models 資料描述結構、驗證和完整性規則等模組 views 生成html的所有模組檔案,也可以存放css、圖片 2.public 儲存rails應用的公共資源,如出錯時的預設頁和首頁等。 3.script 各種指令碼,如程式碼生成器指令碼。 4.test 單元測試和功能測試 5.vendor 程式依賴的外部類庫,和lib一樣都可以被自動載入。 6.config 伺服器、資料庫或其他檔案相依賴的配置檔案 database.yml 資料庫配置 ----adapter資料庫連線庫(介面卡),預設sqlite3 ----database資料庫名稱 ----pool連線池數量 ----timeout經過多少毫秒後伺服器自動放棄連線,預設為5000ms。 7.db 資料庫指令碼 8.doc 文件 9.lib 類庫 10.log 操作日誌 11.其他檔案 .gitignore 記錄哪些是需要忽略,不需要追蹤的檔案 config.ru 基於rack伺服器的配置來啟動應用程式 Gemfile 允許我們指定哪些gem是rails應用程式所依賴的 Rakefile 包含了一些可以在命令列下執行的作業 README 包含了應用程式的簡要說明
五、增加自定義頁面方法
(1)config/routes.rb get "detailreports" => "complianceruns#report" (2)controller中 def report xx render :report end (3) views/complianceruns/中新建report.html.erb
namespace :test do task :hello do puts 'hello' end end 執行: rake test:hello
七、rails發郵件 1) update the /etc/postfix/main.cf by adding the following settings in the end: smtp_sasl_auth_enable = yes smtp_sasl_password_maps = static:使用者:密碼 smtp_sasl_security_options = noanonymous smtp_tls_security_level = encrypt smtp_tls_CAfile = /etc/postfix/ssl/gd_bundle-g2-g1.crt header_size_limit = 4096000 relayhost = [smtp.sendgrid.net]:587 assuming to use sendgrid, and I had a trial account as specified in smtp_sasl_password_maps 2) download the CA file specifed in 1) cd /etc/postfix/ssl wget https://certs.godaddy.com/repository/gd_bundle-g2-g1.crt 3) restart the postfix /etc/init.d/postfix restart 4) it may need to install a missing moduel yum install cyrus-sasl-plain 1.Gemfile中增加 gem 'rake', '11.3.0' 2.專案根目錄執行 rails g mailer UserMailer 3.vi app/mailers/user_mailer 增加 default from: "[email protected]" def send_mail(params = {}) @url = 'http://example.com/login' mail( :subject => 'abc', :to => "[email protected]", :from => '[email protected]', :date => Time.now ) end 4.vi config/environments/development.rb 增加 ActionMailer::Base.delivery_method = :smtp config.action_mailer.perform_deliveries = true config.action_mailer.raise_delivery_errors = true config.action_mailer.default :charset => "utf-8" config.action_mailer.default_url_options = { :host => 'localhost:3000' } ActionMailer::Base.smtp_settings = { :address => "smtp.163.com", :port => 25, :domain => "163.com", :authentication => :login, :user_name => "[email protected]", :password => "xx" }
八、專案中增加bootstrap (1)、在Gemfile中增加 gem 'bootstrap-sass', '~> 3.2.0.2' (2)、bundle install (3)、把assets/stylesheets/application.css重新命名為application.css.scss (4)、在這個檔案中增加: @import "bootstrap-sprockets"; @import "bootstrap"; (5)、在assets/javascriptsheets/application.js中增加://= require bootstrap-sprockets 九、分頁 will_paginate .paginate(:per_page => pageSize, :page => pageNumber) 十、匯出csv def export_to_csv logger.debug "whyrun report export start: #{DateTime.now}" startDateUnixTime = params[:startDateUnixTime] endDateUnixTime = params[:endDateUnixTime] searchString = params[:searchString] searchColumns = params[:searchColumns] if validate_date_in_millisecs(startDateUnixTime) || validate_date_in_millisecs(endDateUnixTime) || validate_string(searchString,'searchString') || validate_string(searchColumns,'searchColumns') return end options = { :startDateUnixTime => startDateUnixTime, :endDateUnixTime => endDateUnixTime, :searchString => searchString, :searchColumns => searchColumns, } whyrun_reports = WhyrunReport.search(options) logger.debug "write file start: #{DateTime.now}" time = Time.now.strftime('%Y%m%d%H%M%S') zipstream = Zip::OutputStream.write_buffer do |zos| zos.put_next_entry "Compliance_Check_Report_#{time}.csv" zos.print "Server, Platform, Start Time, Tech spec, Policy, Validation, Policy Attribute, Required Value, Current Value, Compliant, Action to Remediate, Environment, Profile, Description \n" for i in 0..whyrun_reports.length-1 server = whyrun_reports[i]['server'] || '' platform = whyrun_reports[i]['platform'] || '' startTime = whyrun_reports[i].starttime.strftime('%Y-%m-%dT%H:%M:%S.%3NZ') || '' techspec = whyrun_reports[i]['techspec'] || '' environment = whyrun_reports[i]['environment'] || '' profile = whyrun_reports[i]['profile'] || '' description = whyrun_reports[i]['description'] || '' data = [server, platform, startTime, techspec, policy, validation, policy_attribute, requiredValue, currentValue, compliant, action_to_remediate, environment, profile, description] zos.print data.to_csv end end zipstream.rewind send_data zipstream.string, filename: "Compliance_Check_Report_#{time}.zip", disposition: 'attachment' logger.debug "export end: #{DateTime.now}" end
cd demo vi Gemfile 末尾end前增加 gem 'execjs' gem 'therubyracer' 2.測試服務是否可用 rails s -b 0.0.0.0 http://localhost:3000/ 3.配置root頁面(可忽略) root to: redirect('/ccconsole/chart') 4.配置資料庫(可忽略)
二、rails生成空資料庫 (1)建立資料庫(只需執行一次,可忽略) rake db:create
四、rails專案目錄結構(程式自動生成) 1.app資料夾(rails的核心部分,也可以說存放的是針對專案的所有程式碼) 包括6個子資料夾 assets 圖片、js和樣式表 controllers 驅動業務邏輯的控制器 helpers 檢視輔助類,一些常用的程式碼段 mailers 與郵件服務相關的類 models 資料描述結構、驗證和完整性規則等模組 views 生成html的所有模組檔案,也可以存放css、圖片 2.public 儲存rails應用的公共資源,如出錯時的預設頁和首頁等。 3.script 各種指令碼,如程式碼生成器指令碼。 4.test 單元測試和功能測試 5.vendor 程式依賴的外部類庫,和lib一樣都可以被自動載入。 6.config 伺服器、資料庫或其他檔案相依賴的配置檔案 database.yml 資料庫配置 ----adapter資料庫連線庫(介面卡),預設sqlite3 ----database資料庫名稱 ----pool連線池數量 ----timeout經過多少毫秒後伺服器自動放棄連線,預設為5000ms。 7.db 資料庫指令碼 8.doc 文件 9.lib 類庫 10.log 操作日誌 11.其他檔案 .gitignore 記錄哪些是需要忽略,不需要追蹤的檔案 config.ru 基於rack伺服器的配置來啟動應用程式 Gemfile 允許我們指定哪些gem是rails應用程式所依賴的 Rakefile 包含了一些可以在命令列下執行的作業 README 包含了應用程式的簡要說明
五、增加自定義頁面方法
(1)config/routes.rb get "detailreports" => "complianceruns#report" (2)controller中 def report xx render :report end (3) views/complianceruns/中新建report.html.erb
六、rails task
namespace :test do task :hello do puts 'hello' end end 執行: rake test:hello
七、rails發郵件 1) update the /etc/postfix/main.cf by adding the following settings in the end: smtp_sasl_auth_enable = yes smtp_sasl_password_maps = static:使用者:密碼 smtp_sasl_security_options = noanonymous smtp_tls_security_level = encrypt smtp_tls_CAfile = /etc/postfix/ssl/gd_bundle-g2-g1.crt header_size_limit = 4096000 relayhost = [smtp.sendgrid.net]:587 assuming to use sendgrid, and I had a trial account as specified in smtp_sasl_password_maps 2) download the CA file specifed in 1) cd /etc/postfix/ssl wget https://certs.godaddy.com/repository/gd_bundle-g2-g1.crt 3) restart the postfix /etc/init.d/postfix restart 4) it may need to install a missing moduel yum install cyrus-sasl-plain 1.Gemfile中增加 gem 'rake', '11.3.0' 2.專案根目錄執行 rails g mailer UserMailer 3.vi app/mailers/user_mailer 增加 default from: "[email protected]" def send_mail(params = {}) @url = 'http://example.com/login' mail( :subject => 'abc', :to => "[email protected]", :from => '[email protected]', :date => Time.now ) end 4.vi config/environments/development.rb 增加 ActionMailer::Base.delivery_method = :smtp config.action_mailer.perform_deliveries = true config.action_mailer.raise_delivery_errors = true config.action_mailer.default :charset => "utf-8" config.action_mailer.default_url_options = { :host => 'localhost:3000' } ActionMailer::Base.smtp_settings = { :address => "smtp.163.com", :port => 25, :domain => "163.com", :authentication => :login, :user_name => "[email protected]", :password => "xx" }
八、專案中增加bootstrap (1)、在Gemfile中增加 gem 'bootstrap-sass', '~> 3.2.0.2' (2)、bundle install (3)、把assets/stylesheets/application.css重新命名為application.css.scss (4)、在這個檔案中增加: @import "bootstrap-sprockets"; @import "bootstrap"; (5)、在assets/javascriptsheets/application.js中增加://= require bootstrap-sprockets 九、分頁 will_paginate .paginate(:per_page => pageSize, :page => pageNumber) 十、匯出csv def export_to_csv logger.debug "whyrun report export start: #{DateTime.now}" startDateUnixTime = params[:startDateUnixTime] endDateUnixTime = params[:endDateUnixTime] searchString = params[:searchString] searchColumns = params[:searchColumns] if validate_date_in_millisecs(startDateUnixTime) || validate_date_in_millisecs(endDateUnixTime) || validate_string(searchString,'searchString') || validate_string(searchColumns,'searchColumns') return end options = { :startDateUnixTime => startDateUnixTime, :endDateUnixTime => endDateUnixTime, :searchString => searchString, :searchColumns => searchColumns, } whyrun_reports = WhyrunReport.search(options) logger.debug "write file start: #{DateTime.now}" time = Time.now.strftime('%Y%m%d%H%M%S') zipstream = Zip::OutputStream.write_buffer do |zos| zos.put_next_entry "Compliance_Check_Report_#{time}.csv" zos.print "Server, Platform, Start Time, Tech spec, Policy, Validation, Policy Attribute, Required Value, Current Value, Compliant, Action to Remediate, Environment, Profile, Description \n" for i in 0..whyrun_reports.length-1 server = whyrun_reports[i]['server'] || '' platform = whyrun_reports[i]['platform'] || '' startTime = whyrun_reports[i].starttime.strftime('%Y-%m-%dT%H:%M:%S.%3NZ') || '' techspec = whyrun_reports[i]['techspec'] || '' environment = whyrun_reports[i]['environment'] || '' profile = whyrun_reports[i]['profile'] || '' description = whyrun_reports[i]['description'] || '' data = [server, platform, startTime, techspec, policy, validation, policy_attribute, requiredValue, currentValue, compliant, action_to_remediate, environment, profile, description] zos.print data.to_csv end end zipstream.rewind send_data zipstream.string, filename: "Compliance_Check_Report_#{time}.zip", disposition: 'attachment' logger.debug "export end: #{DateTime.now}" end