提高 Rails 中对象名称的可读性

编程入门 行业动态 更新时间:2024-10-27 20:31:27
本文介绍了提高 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.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 中对象名称的可读性

本文发布于:2023-11-06 01:53:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1562423.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:可读性   对象   名称   Rails

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!