[ruby] 예외를 발생시키지 않고 Ruby에서 현재 스택 추적을 가져옵니다.

예외가 발생 하지 않고 Rails 3 앱에 현재 역 추적 (stacktrace)을 기록하고 싶습니다 . 어떻게 생각해?

왜 이것을 원합니까? Rails가 템플릿을 찾을 때 수행되는 호출을 추적하려고합니다. 내가 특정 하위 클래스 컨트롤러의 뷰 경로를 변경하고 싶기 때문에 재정의 할 프로세스의 일부를 선택할 수 있습니다.

파일에서 호출하고 싶습니다 : gems\actionpack-3.2.3\lib\action_dispatch\middleware\templates\rescues\missing_template.erb. 모범 사례는 아니지만 템플릿 검색이 발생하는 스택의 다운 스트림임을 알고 있습니다.



답변

당신은 사용할 수 있습니다 Kernel#caller:

# /tmp/caller.rb

def foo
  puts caller # Kernel#caller returns an array of strings
end

def bar
  foo
end

def baz
  bar
end

baz

산출:

caller.rb:8:in `bar'
caller.rb:12:in `baz'
caller.rb:15:in `<main>'


답변

사용해보십시오

Thread.current.backtrace


답변

예외가 발생할 때 사용자 정의 오류 페이지를 표시하기 위해 이것을 사용합니다.

rescue_from Exception do |exception|
  logger.error exception.class
  logger.error exception.message
  logger.error exception.backtrace.join "\n"
  @exception = exception


  # ExceptionNotifier::Notifier.exception_notification env, @exception

  respond_to do |format|
    if [AbstractController::ActionNotFound, ActiveRecord::RecordNotFound, ActionController::RoutingError, ActionController::UnknownAction].include?(exception.class)
      format.html { render :template => "errors/404", :status => 404 }
      format.js   { render :nothing => true, :status => 404 }
      format.xml  { render :nothing => true, :status => 404 }
    elsif exception.class == CanCan::AccessDenied
      format.html {
        render :template => "errors/401", :status => 401 #, :layout => 'application'
      }
      # format.js   { render :json => { :errors => [exception.message] }, :status => 401 }
      # format.js   { render :js => 'alert("Hello 401")' }
      format.js   { render :template => 'errors/401.js.erb' }

    else
      ExceptionNotifier::Notifier.exception_notification(env, exception).deliver
      format.html { render :template => "errors/500", :status => 500 } #, :layout => 'im2/application' }
      # format.js   { render :nothing => true, :status => 500 }
      format.js   { render :template => 'errors/500.js.erb' }

    end
  end
end


답변