顺便说一句,const_get 和qualified_const_get 有什么区别? [英] What's the differences btw const_get and qualified_const_get?

查看:52
本文介绍了顺便说一句,const_get 和qualified_const_get 有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

标准 ruby​​ 库中有一系列方法,即 const_defined?、const_get 或 const_set.

There is a series of methods, i.e., const_defined?, const_get, or const_set, in standard ruby library.

<代码>const_定义?,const_get,常量集

此外,在 Rails 的 Active Support Core Extensions 中,存在针对这些人的合格_"对应项.

And also, in the Active Support Core Extensions of Rails, their "qualified_" counterparts for these individuals exist.

<代码>qualified_const_defined?,qualified_const_get,qualifid_const_set

有没有人可以明确解释这些方法的裸形式和限定形式之间的区别?

Is there anybody who can explain explicitly the differences between bare and qualified forms for these methods?

提前致谢.

推荐答案

qualified_ const 帮助器支持与任意深度的常量交互(不仅仅是主题的子项).

The qualified_ const helpers support interacting with constants at arbitrary depths (not just children of the subject).

我认为一个例子是解释这个问题的最简单方法.假设 Foo::Bar::Baz 存在:

I think an example is the easiest way to explain this one. Let's say Foo::Bar::Baz exists:

 > Object::const_get "Foo::Bar::Baz"
NameError: wrong constant name Foo::Bar::Baz
 > Object::const_get "Foo"
=> Foo
 > Foo.const_get "Bar"
=> Foo::Bar
 > Foo::Bar.const_get "Baz"
=> Foo::Bar::Baz

qualified_ 方法允许您避免直接遍历模块层次结构:

The qualified_ methods allow you to avoid walking the module hierarchy directly:

 > Object::qualified_const_get "Foo::Bar::Baz"
=> Foo::Bar::Baz
 > Foo.qualified_const_set "Bar::Fizz", 123
=> 123
 > Foo::Bar::Fizz
=> 123

I'd recommend poking around the source, too. It's pretty clean.

这篇关于顺便说一句,const_get 和qualified_const_get 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆