0

我很想清理这段代码:

  def insert_general_methods
    inject_into_file "app/controllers/application_controller.rb", after: "protect_from_forgery"  do
      a = "\n\n  private\n\n  def current_user\n"
      b = "    @current_user ||= User.find_by_auth_token!(cookies[:auth_token]) if cookies[:auth_token]\n"
      c = "  end\n"
      d = "\n  helper_method :current_user\n\n"
      e = "  def authorize\n"
      f = "    redirect_to login_url, alert: 'Not authorized. Please login.' if current_user.nil?\n"
      g = "  end\n"
      a+b+c+d+e+f+g
    end
  end

在 Rails 中的 Thor 或 Generator 模块上是否有任何方法可以让我以更优雅的形式注入此方法?

4

1 回答 1

1

使用 heredoc 语法:

 inject_into_file 'app/controllers/application_controller.rb', after: "protect_from_forgery"  do <<-RUBY
   # some code
 RUBY
 end
于 2012-10-19T00:44:12.643 回答