Con đường 1 request lang thang trong Rails
RubyOnRails
39
White

checkraiser viết ngày 31/08/2016

class ApiConstraint
  attr_reader :versions

  def initialize(options)
    @version = options.fetch :version, nil
    @versions = options.fetch :versions, [@version]
  end

  def matches?(request)
    if request.headers.include? :accept
      accept_header = request.headers.fetch :accept

      if accept_header.include? 'version='
        versions.any? do |version|
          accept_header.include? "version=#{version}"
        end
      end
    end
  end
end

2.

module ActionDispatch
  module Routing
    class Mapper
        def matches?(req)
          @constraints.all? do |constraint|
            (constraint.respond_to?(:matches?) && constraint.matches?(req)) ||
              (constraint.respond_to?(:call) && constraint.call(*constraint_args(constraint, req)))
          end
        end
...

3.

def serve(req)
          return [ 404, {'X-Cascade' => 'pass'}, [] ] unless matches?(req)

          if dispatcher?
            @app.serve req

4.

module ActionDispatch
  module Routing
    # :stopdoc:
    class RouteSet
      def serve(req)
          req.check_path_parameters!
          params = req.path_parameters

          prepare_params!(params)

          # Just raise undefined constant errors if a controller was specified as default.
          unless controller = controller(params, @defaults.key?(:controller))
            return [404, {'X-Cascade' => 'pass'}, []]
          end

          dispatch(controller, params[:action], req.env)
        end
module ActionDispatch
  module Routing
    # :stopdoc:
    class RouteSet
       def dispatch(controller, action, env)
          controller.action(action).call(env)
        end

5.

module ActionController
  # Extend ActionDispatch middleware stack to make it aware of options
  # allowing the following syntax in controllers:
  #
  #   class PostsController < ApplicationController
  #     use AuthenticationMiddleware, except: [:index, :show]
  #   end
  #
  class MiddlewareStack < ActionDispatch::MiddlewareStack #:nodoc:
    class Middleware < ActionDispatch::MiddlewareStack::Middleware #:nodoc:
        def self.action(name, klass = ActionDispatch::Request)
          if middleware_stack.any?
            middleware_stack.build(name) do |env|
              new.dispatch(name, klass.new(env))
            end
          else
            lambda { |env| new.dispatch(name, klass.new(env)) }
          end
        end

6.

module ActionView
    def initialize(*) # :nodoc:
      @_action_has_layout = true
      super
    end

7.

module ActionDispatch
  module Routing
    def initialize(*)
        @_routes = nil
        super
      end

8.

module ActionController
    class Metal < AbstractController::Base
        def initialize
          @_headers = {"Content-Type" => "text/html"}
          @_status = 200
          @_request = nil
          @_response = nil
          @_routes = nil
          super
    end

9.

module ActionDispatch
  class Request < Rack::Request
    def initialize(env)
      super
      @method            = nil
      @request_method    = nil
      @remote_ip         = nil
      @original_fullpath = nil
      @fullpath          = nil
      @ip                = nil
      @uuid              = nil
    end

10.

module ActionDispatch
  module Http
    def initialize(env)
        super
        @protocol = nil
        @port     = nil
      end

11.

module ActionDispatch
  module Http
    # Allows you to specify sensitive parameters which will be replaced from
    # the request log by looking in the query string of the request and all
    # sub-hashes of the params hash to filter. If a block is given, each key and
    # value of the params hash and all sub-hashes is passed to it, the value
    # or key can be replaced using String#replace or similar method.
    #
    #   env["action_dispatch.parameter_filter"] = [:password]
    #   => replaces the value to all keys matching /password/i with "[FILTERED]"
    #
    #   env["action_dispatch.parameter_filter"] = [:foo, "bar"]
    #   => replaces the value to all keys matching /foo|bar/i with "[FILTERED]"
    #
    #   env["action_dispatch.parameter_filter"] = lambda do |k,v|
    #     v.reverse! if k =~ /secret/i
    #   end
    #   => reverses the value to all keys matching /secret/i
    module FilterParameters
      ENV_MATCH = [/RAW_POST_DATA/, "rack.request.form_vars"] # :nodoc:
      NULL_PARAM_FILTER = ParameterFilter.new # :nodoc:
      NULL_ENV_FILTER   = ParameterFilter.new ENV_MATCH # :nodoc:

      def initialize(env)
        super
        @filtered_parameters = nil
        @filtered_env        = nil
        @filtered_path       = nil
      end

12.

module Rack
  # Rack::Request provides a convenient interface to a Rack
  # environment.  It is stateless, the environment +env+ passed to the
  # constructor will be directly modified.
  #
  #   req = Rack::Request.new(env)
  #   req.post?
  #   req.params["data"]

  class Request
    # The environment of the request.
    attr_reader :env

    def initialize(env)
      @env = env
    end

13.

module ActionController
  module RackDelegation
    private

    def set_response!(request)
      @_response         = ActionDispatch::Response.new
      @_response.request = request
    end

14.

module ActionController
  module RackDelegation
    extend ActiveSupport::Concern

    delegate :headers, :status=, :location=, :content_type=,
             :status, :location, :content_type, :response_code, :to => "@_response"

    def dispatch(action, request)
      set_response!(request)
      super(action, request)
    end

15.

module ActionController
    class Metal < AbstractController::Base
        def dispatch(name, request) #:nodoc:
      @_request = request
      @_env = request.env
      @_env['action_controller.instance'] = self
      process(name)
      to_a
    end

16.

module ActionView
    module Rendering
    extend ActiveSupport::Concern
    include ActionView::ViewPaths

    # Overwrite process to setup I18n proxy.
    def process(*) #:nodoc:
      old_config, I18n.config = I18n.config, I18nProxy.new(I18n.config, lookup_context)
      super
    ensure
      I18n.config = old_config
    end

17.

module AbstractController
    class Base
        def process(action, *args)
      @_action_name = action.to_s

      unless action_name = _find_action_name(@_action_name)
        raise ActionNotFound, "The action '#{action}' could not be found for #{self.class.name}"
      end

      @_response_body = nil

      process_action(action_name, *args)
    end

18.

module ActiveRecord
  module Railties # :nodoc:
    module ControllerRuntime #:nodoc:
      extend ActiveSupport::Concern

    protected

      attr_internal :db_runtime

      def process_action(action, *args)
        # We also need to reset the runtime before each action
        # because of queries in middleware or in cases we are streaming
        # and it won't be cleaned up by the method below.
        ActiveRecord::LogSubscriber.reset_runtime
        super
      end

19.

module ActionController
    def process_action(*args)
      if _wrapper_enabled?
        if request.parameters[_wrapper_key].present?
          wrapped_hash = _extract_parameters(request.parameters)
        else
          wrapped_hash = _wrap_parameters request.request_parameters
        end

        wrapped_keys = request.request_parameters.keys
        wrapped_filtered_hash = _wrap_parameters request.filtered_parameters.slice(*wrapped_keys)

        # This will make the wrapped hash accessible from controller and view
        request.parameters.merge! wrapped_hash
        request.request_parameters.merge! wrapped_hash

        # This will display the wrapped hash in the log file
        request.filtered_parameters.merge! wrapped_filtered_hash
      end
      super
    end

20.

module ActionController
  # Adds instrumentation to several ends in ActionController::Base. It also provides
  # some hooks related with process_action, this allows an ORM like Active Record
  # and/or DataMapper to plug in ActionController and show related information.
  #
  # Check ActiveRecord::Railties::ControllerRuntime for an example.
  module Instrumentation
    extend ActiveSupport::Concern

    include AbstractController::Logger
    include ActionController::RackDelegation

    attr_internal :view_runtime

    def process_action(*args)
      raw_payload = {
        :controller => self.class.name,
        :action     => self.action_name,
        :params     => request.filtered_parameters,
        :format     => request.format.try(:ref),
        :method     => request.request_method,
        :path       => (request.fullpath rescue "unknown")
      }

      ActiveSupport::Notifications.instrument("start_processing.action_controller", raw_payload.dup)

      ActiveSupport::Notifications.instrument("process_action.action_controller", raw_payload) do |payload|
        begin
          result = super
          payload[:status] = response.status
          result
        ensure
          append_info_to_payload(payload)
        end
      end
    end

21.

module ActionView

Bình luận


White
{{ comment.user.name }}
Bỏ hay Hay
{{comment.like_count}}
Male avatar
{{ comment_error }}
Hủy
   

Hiển thị thử

Chỉnh sửa

White

checkraiser

12 bài viết.
16 người follow
Kipalog
{{userFollowed ? 'Following' : 'Follow'}}
Cùng một tác giả
White
6 1
Tôi dự sẽ viết 1 loạt series về việc thiết kế 1 ứng dụng Rails như thế nào để nó có thể giúp bạn ăn ngon ngủ yên trong hằng năm trời: Khi mà việc t...
checkraiser viết hơn 2 năm trước
6 1
White
5 9
Cũng ngót nghét đi làm hơn 6 năm rồi, mình chỉ thấy một điều khá "ngược đời": Các ông chủ , những người trả tiền cho bạn lại có tư duy lập trình ké...
checkraiser viết 5 tháng trước
5 9
White
3 1
This post is a sample chapter from my (Link) How to render a ReactJS component isomorphically ? The trick is in defaultProps and componentDidM...
checkraiser viết hơn 2 năm trước
3 1
Bài viết liên quan
White
8 1
Tiếp theo (Link) Mình sẽ hướng dẫn cách test căn bản cho API mình tạo. Thật ra mà nói thì mình phải viết test trước khi làm nhưng mà để tránh việc...
My Mai viết hơn 2 năm trước
8 1
White
7 4
Nếu ai đã làm Rails thì không còn lạ lẫm gì với chức năng Migration của Rails. Nếu ai chưa biết thì tôi xin giới thiệu sơ qua chức năng này. Rails ...
Lơi Rệ viết gần 3 năm trước
7 4
White
0 0
Performance regression in ActiveRecord model instance creation in Rails 4.1.x When you guys met the performance issue in Rails 4.1.x. And after be...
Luu Nguyen viết hơn 1 năm trước
0 0
{{like_count}}

kipalog

{{ comment_count }}

bình luận

{{liked ? "Đã kipalog" : "Kipalog"}}


White
{{userFollowed ? 'Following' : 'Follow'}}
12 bài viết.
16 người follow

 Đầu mục bài viết

Vẫn còn nữa! x

Kipalog vẫn còn rất nhiều bài viết hay và chủ đề thú vị chờ bạn khám phá!