0

I would love to clean this code up:

  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

Is there any method on Thor or Generator Module in Rails that allows me to inject this method in a more elegant form?

Thanks for all the fish
  • 1,671
  • 3
  • 17
  • 31

1 Answers1

1

Use heredoc syntax:

 inject_into_file 'app/controllers/application_controller.rb', after: "protect_from_forgery"  do <<-RUBY
   # some code
 RUBY
 end
Michael Johnston
  • 5,298
  • 1
  • 29
  • 37