过滤器:在action动作之前,之后或者周围执行指定的动作
#一般用法
#所有的继承ApplicationController类的都会执行before_action
class ApplicationController < ActionController::Base
before_action :require_login
private
def require_login
unless logged_in?
flash[:error] = "You must be logged in to access this section"
redirect_to new_login_url # halts request cycle
end
end
end
#通过skip_before_action跳过before_action方法
class LoginsController < ApplicationController
skip_before_action :require_login, only: [:new, :create]
#skip_before_action :require_login, except: [:new, :create]
end
#其他用法,guides中有代码演示
1.直接在before_action块中调用方法
2.为了代码复用,定义存在before_action的类
3.around_action中,使用transaction的方式
request && response
#request对象
host 请求的主机名
domain(n=2) 主机名的前 n 个片段,从顶级域名的右侧算起
format 客户端请求的内容类型
method 请求使用的 HTTP 方法
get?, post?, patch?, put?, delete?, head? 如果 HTTP 方法是 GET/POST/PATCH/PUT/DELETE/HEAD,返回 true
headers 返回一个散列,包含请求的首部
port 请求的端口号(整数)
protocol 返回所用的协议外加 "://",例如 "http://"
query_string URL 中的查询字符串,即 ? 后面的全部内容
remote_ip 客户端的 IP 地址
url 请求的完整 URL
#response对象
body 回送客户端的数据,字符串格式。通常是 HTML。
status 响应的 HTTP 状态码,例如,请求成功时是 200,文件未找到时是 404。
location 重定向的 URL(如果重定向的话)。
content_type 响应的内容类型。
charset 响应使用的字符集。默认是 "utf-8"。
headers 响应的首部。
验证
#http基本身份验证
class AdminsController < ApplicationController
http_basic_authenticate_with name: "humbaba", password: "5baa61e4"
end
#http摘要身份验证
class AdminsController < ApplicationController
USERS = { "lifo" => "world" }
before_action :authenticate
private
def authenticate
authenticate_or_request_with_http_digest do |username|
USERS[username]
end
end
end
日志过滤
#config/environments/developments.rb
config.filter_parameters << :password #过滤参数,日志中会显示为[FILTERED]
config.filter_redirect << 's3.amazonaws.com' #过滤重定向
config.filter_redirect.concat ['s3.amazonaws.com', /private_path/] #匹配的url会显示[FILTERED],经过测试没有作用
rescue的两种方式:ruby的rescue和rails的rescue_from
#使用rescue形式
class UsersController < ApplicationController
def show
begin
@article = Article.find(params[:id])
rescue ActiveRecord::RecordNotFound
@articles = Article.all
render 'index'
flash[:notice] = "what you search is not found"
end
end
end
#使用rescue_from的形式
class ApplicationController < ActionController::Base
rescue_from ActiveRecord::RecordNotFound, with: :record_not_found
private
def record_not_found
render plain: "404 Not Found", status: 404
end
end
#定制rescue_from的异常类
class ApplicationController < ActionController::Base
rescue_from User::NotAuthorized, with: :user_not_authorized
private
def user_not_authorized
flash[:error] = "You don't have access to this section."
redirect_back(fallback_location: root_path)
end
end
class ClientsController < ApplicationController
# Check that the user has the right authorization to access clients.
before_action :check_authorization
# Note how the actions don't have to worry about all the auth stuff.
def edit
@client = Client.find(params[:id])
end
private
# If the user is not authorized, just throw the exception.
def check_authorization
raise User::NotAuthorized unless current_user.admin?
end
end