Rails extend main 的作业

ane · 2014年09月13日 · 最后由 ane 回复于 2014年09月13日 · 1914 次阅读

先上代码吧

require 'thread_safe'
require 'active_support/core_ext/array/prepend_and_append'
require 'active_support/i18n'

module ActiveSupport
  module Inflector
    extend self

    # A singleton instance of this class is yielded by Inflector.inflections,
    # which can then be used to specify additional inflection rules. If passed
    # an optional locale, rules for other languages can be specified. The
    # default locale is <tt>:en</tt>. Only rules for English are provided.
    #
    #   ActiveSupport::Inflector.inflections(:en) do |inflect|
    #     inflect.plural /^(ox)$/i, '\1\2en'
    #     inflect.singular /^(ox)en/i, '\1'
    #
    #     inflect.irregular 'octopus', 'octopi'
    #
    #     inflect.uncountable 'equipment'
    #   end
    #
    # New rules are added at the top. So in the example above, the irregular
    # rule for octopus will now be the first of the pluralization and
    # singularization rules that is runs. This guarantees that your rules run
    # before any of the rules that may already have been loaded.
    class Inflections
     ....
    end

    # Yields a singleton instance of Inflector::Inflections so you can specify
    # additional inflector rules. If passed an optional locale, rules for other
    # languages can be specified. If not specified, defaults to <tt>:en</tt>.
    # Only rules for English are provided.
    #
    #   ActiveSupport::Inflector.inflections(:en) do |inflect|
    #     inflect.uncountable 'rails'
    #   end
    def inflections(locale = :en)
      if block_given?
        yield Inflections.instance(locale)
      else
        Inflections.instance(locale)
      end
    end
  end
end

这是 rails 的 Inflector.rb 的代码结构,一直疑问这个 self 是什么,ActiveSupport::Inflector.inflections {p self}发现居然是‘main’。不解了,这个为何要继承这个 main?

在 module 内部 extend self 相当于 module_function 声明。

就是为了让一个 module 可以 include 到一个 class 里使用,也可以直接 ActiveSupport::Inflector.inflections 这样调用。

#1 楼 @hooopo 那这里是相当于 include 到 哪个 class 了?

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