在过滤异常之前将常量传递给rails

时间:2018-05-29 12:46:08

标签: ruby-on-rails ruby ruby-on-rails-4

我有几个过滤器类似于: @objc func image(_ image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: UnsafeRawPointer) { if let error = error { // we got back an error! let ac = UIAlertController(title: "Save error", message: error.localizedDescription, preferredStyle: .alert) ac.addAction(UIAlertAction(title: "OK", style: .default)) present(ac, animated: true) } else { let ac = UIAlertController(title: "Saved!", message: "The image has been saved to your photos.", preferredStyle: .alert) ac.addAction(UIAlertAction(title: "OK", style: .default)) present(ac, animated: true) } }

但是在过滤之前我有3或4个例外。起初我打算改变所有before_filter方法中的逻辑,但我发现自己重复了很多代码。在一个更完美的世界里,我会为我想要添加的动作设置一个单独的控制器,但是我必须在同一个控制器中添加动作,并解决已经存在的结构。

我想要做的是使用我想要在之前的过滤器中跳过的方法创建一个常量或变量,例如

before_filter :setup_plan, except: :some_action, :another_action, :yet_another_action

然后只需使用ACTIONS_TO_SKIP = [:some_action, :another_action, :yet_another_action]

执行此操作时,我得到一个未初始化的常量错误。我尝试将其移动到帮助器中的方法,并且还得到了未定义的方法错误。 我知道我错过了什么,但无法弄清楚。是否真的没有办法传递一个方法或常量,它返回我想要在之前的过滤器中跳过的方法数组?只是想让我的控制器更清洁,更简洁。

2 个答案:

答案 0 :(得分:1)

您需要在跳过调用之前声明常量。该文件自上而下解释。

class FoosController
  ACTIONS_TO_SKIP = [:yes, :this, :and, :something, :more]

  before_filter :setup_plan, except: ACTIONS_TO_SKIP
end

请注意,在最近的Rails版本中,现在称为before_actionRails 4: before_filter vs. before_action (也许你想升级......)

答案 1 :(得分:0)

您可以尝试这样的事情:

before_filter :my_before_filter, if: :action_to_skip?

def action_to_skip?
  %w[some_action another_action yet_another_action].member?(action_name)
end