在Rails中寻找current_ *方法的代码部分的好地方

时间:2015-09-17 21:17:26

标签: ruby-on-rails coding-style

问题基本上是关于良好的代码风格。

目前正在开发一个包含大量current_usercurrent_style等方法的大型项目,可以从控制器和视图中调用这些方法。 现在我在ApplicationController中定义了这些方法,但我认为控制器是针对' action'方法。喜欢' index','编辑'等,而不是定义这些额外的方法。 保留这些方法的最佳位置是什么? 我正在考虑帮助程序,但它们是为了从代码中卸载视图而不是为了这些东西。 关注? ApplicationController的?助手?

2 个答案:

答案 0 :(得分:1)

我的投票是关注。在您的应用程序控制器中添加此行。姓名不是最好的,但现在就足够了。

include Concerns::Currentable

然后在app / controllers / concerns / currentable.rb中添加如下内容:

module Concerns::Currentable
  extend ActiveSupport::Concern

  included do
    helper_method :current_user
  end

  def current_user
    # ...
  end
  protected :current_user

  def current_method_that_isnt_a_helper
    # ...
  end
  protected :current_method_that_isnt_a_helper

end

通过这种方式,您可以明确控制器可用的内容以及视图可用的内容,并将它们标记为受保护,它们不会错误地显示为捕获所有路径中的操作。

答案 1 :(得分:1)

它们应该在助手和控制器之间分开。

String textToRemove = "xsi:schemaLocation=\"http://www.hello.org/abcss-4_2 http://www.hello.org/v4-2/abcss-4-2.xsd\""; String data = readFromFile("path", "filename.xml"); data = data.replaceAll(textToRemove, ""); System.out.println(data); 通常在控制器中定义,但也可以在帮助程序中使用(通过public static void deposit(String account, String amount) throws FileNotFoundException { int i=-2; try{ Scanner file = new Scanner(new File("info.txt")); String line = file.nextLine(); String[] tokens = line.split(" "); do { i++; i++; } while (account!=tokens[i]); int ballance = Integer.parseInt(tokens[i]); int deposit = Integer.parseInt(amount); int updated = (ballance+deposit); tokens[i] = Integer.toString(updated); System.out.println("Your new ballance is $"+tokens[i]); PrintWriter fileOut = new PrintWriter("info.txt"); } catch(FileNotFoundException e){ //handling code } finally{ fileOut.close(); file.close(); )。

current_userhelper_method等也主要是控制器问题。

current_organization应该转到帮助者,current_employeecurrent_style以及与视图相关的所有内容。