Câu hỏi phỏng vấn Ruby on Rails
Câu hỏi

What Are Filters? And How Many Ty...

Câu trả lời

In Ruby on Rails, filters are methods that run at specific points during the request-response cycle of a web application. They allow developers to execute code before, after, or around a controller action, providing a way to manage tasks such as authentication, logging, and performance monitoring.

Types of Filters in Ruby on Rails

  1. Before Filters:

    • Execution: These filters run before a controller action is executed.
    • Use Cases: Commonly used for tasks like user authentication, setting up variables, or checking permissions.
    • Example:
      ruby Copy
      class ApplicationController < ActionController::Base
        before_action :authenticate_user
      
        private
      
        def authenticate_user
          redirect_to login_path unless current_user
        end
      end
    • Behavior: If a before filter halts the request (e.g., by redirecting), the action will not be executed, and subsequent filters will also be skipped[1][2][5][6][9].
  2. After Filters:

    • Execution: These filters run after a controller action has been executed and a response has been prepared.
    • Use Cases: Typically used for tasks like logging, cleanup operations, or modifying the response.
    • Example:
      ruby Copy
      class ApplicationController < ActionController::Base
        after_action :log_request
      
        private
      
        def log_request
          Rails.logger.info("Request processed for #{request.path}")
        end
      end
    • Behavior: After filters cannot halt the request cycle since the action has already been executed[1][2][5][6][9].
  3. Around Filters:

    • Execution: These filters wrap around a controller action, running code both before and after the action.
    • Use Cases: Useful for tasks that need to encompass the entire action, such as performance monitoring or exception handling.
    • Example:
      ruby Copy
      class ApplicationController < ActionController::Base
        around_action :measure_time
      
        private
      
        def measure_time

...

senior

senior

Gợi ý câu hỏi phỏng vấn

junior

Mention what is the difference between a gem and a plugin in Ruby?

junior

Explain what is Rails Active Record in Ruby on Rails?

middle

What Is The Difference Between Delete And Destroy ?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào