鉴于在 Rails 上命名对象的约定是这样的:
Given that the convention for naming an object on Rails is like that :
/app/models/foo/bar.rb => class Foo::Bar如果我有一个文件夹结构:
if I have a folder structure :
/app/models/foo/bar/object1.rb /app/models/foo/bar/object2.rb /app/models/foo/main.rb要从我的主要调用这个对象,我必须这样做:
To call this objects from my main, I have to do :
class Foo::Main def some_method Foo::Bar::Object1.new Foo::Bar::Object2.new end end这个工作正常.但我的问题是:
This work fine. But here my question :
有没有办法提高对象名称的可读性?
鉴于在我的 Foo::Main 中位于相同的命名空间 Foo 中;有没有办法用较短的名称调用它们(Foo::Bar::Object1.new 和 Foo::Bar::Object2.new)?
Given that in my Foo::Main is in the same namespace Foo; Is there a way to call them (Foo::Bar::Object1.new and Foo::Bar::Object2.new) with a shorter name ?
我想将它们命名为 Bar::Object1.new 和 Bar::Object2.new,在这种情况下(或 Object1.newcode> 和 Object2.new)
I would like to name them Bar::Object1.new and Bar::Object2.new, in this context (or Object1.new and Object2.new)
class Foo::Main def some_method Bar::Object1.new Bar::Object2.new end end此代码是我所期望的示例,但它不起作用.
This code is an exemple of what I'm expected, but it don't work.
推荐答案如果你想使用顶层模块,你需要使用没有 A::B 简写的嵌套:
If you want to use the top module, you need to use nesting without the A::B shorthand:
module Foo class Main def some_method Bar::Object1.new Bar::Object2.new end end end来源:
- blog.honeybadger.io/avoid-these-traps-when-nesting-ruby-modules/
- techblog.thescore/2014/05/28/how-you-nest-modules-matters-in-ruby/
更多推荐
提高 Rails 中对象名称的可读性
发布评论