新手问题 关于 Rails 中的 Helper 的问题

ibachue · 2012年10月07日 · 2978 次阅读

Hi 大家好, 请教大家一个简单的 Rails 问题: 以下是 Rails 中关于 Helpers 的部分代码,在这段代码中,我唯一奇怪的是,Rails 为啥总是要为 helper 创建一个新的匿名 module(看 included 方法的 block),然后再将对应的 XxxxxHelper 模块 include 进这个 module,而不是直接使用 XxxxxHelper 这个已经写好的模块呢,我觉得这样做的话效率应该更高啊?以后如果有什么新的 helper 也可以直接 include 进 XxxxxHelper 啊,效果完全一样吧。 是不是有什么特殊原因导致不能这么做呢?谢谢大家解答

module AbstractController
  module Helpers
    extend ActiveSupport::Concern
    include Rendering

    included do
      class_attribute :_helpers
      self._helpers = Module.new

      class_attribute :_helper_methods
      self._helper_methods = Array.new
    end

    module ClassMethods
      # When a class is inherited, wrap its helper module in a new module.
      # This ensures that the parent class's module can be changed
      # independently of the child class's.
      def inherited(klass)
        helpers = _helpers
        klass._helpers = Module.new { include helpers }
        klass.class_eval { default_helper_module! unless anonymous? }
        super
      end

      def default_helper_module!
        module_name = name.sub(/Controller$/, '')
        module_path = module_name.underscore
        helper module_path
      rescue MissingSourceFile => e
        raise e unless e.is_missing? "helpers/#{module_path}_helper"
      rescue NameError => e
        raise e unless e.missing_name? "#{module_name}Helper"
      end

      ......
暂无回复。
需要 登录 后方可回复, 如果你还没有账号请 注册新账号