如何檢測到我在Rails中存在不存在的動作的before_filter
?檢測Rails中不存在的動作的before_filter
class PostsController < ApplicationController
before_action :authorize_user, only: [:kreate]
def create
end
end
如何檢測到我在Rails中存在不存在的動作的before_filter
?檢測Rails中不存在的動作的before_filter
class PostsController < ApplicationController
before_action :authorize_user, only: [:kreate]
def create
end
end
你不行。
這就是爲什麼你需要有測試用例。在這種情況下,他們可能會抓到它,因爲authorize_user
不會觸發,因爲您由於拼寫錯誤而將其應用於不存在的操作。
這是一個直截了當的黑客攻擊,但我能想到的檢查過濾器的唯一方法是初始化。以下檢查控制器是否有使用不存在動作的前/後過濾器,並在出現異常消息時產生一個異常消息
# config/initializers/before_filters.rb
# require all controllers
Dir['app/controllers/*'].each do |path|
require path.split('/').last if path.include? '.rb'
end
# get array of all controllers
controllers = ApplicationController.descendants
controllers.each do |controller|
# get all filters for this controller
filters = controller._process_action_callbacks
# get all actions under this controller
actions = controller.action_methods.to_a
filters.each do |filter|
# get all action_conditions for this filter
action_conditions = filter.instance_variable_get(:@if)
# raise error message if action used in filter not in available controller actions
action_conditions.each do |action_condition|
if actions.none? {|action| action_condition.include? action }
message = "#{controller.name} has a #{filter.kind.to_s} filter with a non-existant action (#{action_condition.scan(/'([^']*)'/)[0][0]})"
raise message
end
end
end
end