检查view中flash、session来自何处时

[2] pry(#<#>)> method(:flash).source_location
=> ["/home/z/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/actionview-5.0.2/lib/action_view/helpers/controller_helper.rb", 10]


可得知这些方法都被委托到:controller上,而:controller是一种叫attr_internal的东西

module ActionView
  module Helpers
    # This module keeps all methods and behavior in ActionView
    # that simply delegates to the controller.
    module ControllerHelper #:nodoc:
      attr_internal :controller, :request

      delegate :request_forgery_protection_token, :params, :session, :cookies, :response, :headers,
               :flash, :action_name, :controller_name, :controller_path, :to => :controller

      def assign_controller(controller)
        if @_controller = controller
          @_request = controller.request if controller.respond_to?(:request)
          @_config  = controller.config.inheritable_copy if controller.respond_to?(:config)
          @_default_form_builder = controller.default_form_builder if controller.respond_to?(:default_form_builder)
        end
      end

      def logger
        controller.logger if controller.respond_to?(:logger)
      end
    end
  end
end


去看看attr_internal是什么

[9] pry(#<#>)> self.class.method(:attr_internal).source_location
=> ["/home/z/.rbenv/versions/2.3.3/lib/ruby/gems/2.3.0/gems/activesupport-5.0.2/lib/active_support/core_ext/module/attr_internal.rb", 14]


源码如下

class Module
  # Declares an attribute reader backed by an internally-named instance variable.
  def attr_internal_reader(*attrs)
    attrs.each {|attr_name| attr_internal_define(attr_name, :reader)}
  end

  # Declares an attribute writer backed by an internally-named instance variable.
  def attr_internal_writer(*attrs)
    attrs.each {|attr_name| attr_internal_define(attr_name, :writer)}
  end

  # Declares an attribute reader and writer backed by an internally-named instance
  # variable.
  def attr_internal_accessor(*attrs)
    attr_internal_reader(*attrs)
    attr_internal_writer(*attrs)
  end
  alias_method :attr_internal, :attr_internal_accessor

  class << self; attr_accessor :attr_internal_naming_format end
  self.attr_internal_naming_format = '@_%s'

  private
    def attr_internal_ivar_name(attr)
      Module.attr_internal_naming_format % attr
    end

    def attr_internal_define(attr_name, type)
      internal_name = attr_internal_ivar_name(attr_name).sub(/\A@/, '')
      # use native attr_* methods as they are faster on some Ruby implementations
      send("attr_#{type}", internal_name)
      attr_name, internal_name = "#{attr_name}=", "#{internal_name}=" if type == :writer
      alias_method attr_name, internal_name
      remove_method internal_name
    end
end


简单来说,它跟attr_accessor类似,但它会令xxx访问的@_xxx实例变量,而非@xxx

此外,它也可只定义reader或writer