新手问题 locale 这个变量来自何方?

dimos · 2016年09月30日 · 最后由 martin91 回复于 2016年09月30日 · 2313 次阅读

发现 Rails 中有一个变量 locale,可以在 controller 和 view 中访问。找了半天也没找到出处,请大家解惑。

@Reicampo 中就有使用

def create
  @user = User.new params.require(:user).permit(:username, :email, :name, :password).merge(locale: locale)
  if @user.save
    login_as @user
    UserMailer.confirmation(@user.id).deliver
    redirect_back_or_default root_url
  else
    render :new
  end
end

我都忘了,推荐用 I18n.locale

感谢 @Rei 的回复,I18n.locale 没问题,就是比较好奇 locale 这个变量到底从哪来。 发现 2 年前就有人问这个问题了 stackoverflow

3 楼 已删除

#2 楼 @dimos locale 是 actionview 里边的代理方法:

[1] pry(#<HomeController>)> show-source locale

From: /Users/martin/.rvm/gems/ruby-2.3.1/gems/actionview-5.0.0/lib/action_view/view_paths.rb @ line 11:
Owner: ActionView::ViewPaths
Visibility: public
Number of lines: 2

delegate :template_exists?, :any_templates?, :view_paths, :formats, :formats=,
         :locale, :locale=, :to => :lookup_context

lookup_context 方法定义如下:

def lookup_context
  @_lookup_context ||=
    ActionView::LookupContext.new(self.class._view_paths, details_for_lookup, _prefixes)
end

ActionView::LookupContext 中有相关的实现代码:

module ActionView
  class LookupContext
    def locale
      @details[:locale].first
    end

    # Overload locale= to also set the I18n.locale. If the current I18n.config object responds
    # to original_config, it means that it has a copy of the original I18n configuration and it's
    # acting as proxy, which we need to skip.
    def locale=(value)
      if value
        config = I18n.config.respond_to?(:original_config) ? I18n.config.original_config : I18n.config
        config.locale = value
      end

      super(default_locale)
    end
  end
end

天色已晚,我就不深入研究了,反正路是这条路,还可以继续看 LookupContext 里的 self.register_detail 方法定义以及调用。

另外,Ruby 全局变量名是用 $ 开头的,如果遇到一个看起来像变量但又有全局特性的“变量”的话,基本可以判断其实它是一个方法了。

另外,像这种生僻方法,还是减少使用比较好,增加同一项目共同维护者的负担。还是用 I18n.locale 就好了。

#4 楼 @martin91 太感谢了,之前是一点思路都没,我再仔细看看。

#4 楼 @martin91 show-source locale 之前都执行了哪些代码?

#6 楼 @cisolarix 在 controller action 里边放了个断点 binding.pry

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