提高 Rails 中对象名称的可读性 [英] Improve readability of object name in Rails

查看:29
本文介绍了提高 Rails 中对象名称的可读性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于在 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.newFoo::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.newBar::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

来源:

这篇关于提高 Rails 中对象名称的可读性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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