从单独的文件中包含一个 Ruby 类 [英] Including a Ruby class from a separate file

查看:23
本文介绍了从单独的文件中包含一个 Ruby 类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一段时间以来,我一直在 Ruby 模块中包含一个完整的类.显然这不是我应该做的.似乎模块的重点是存储函数,然后可以将这些函数作为方法包含在新类中.

For a while I had been including an entire class inside of a Ruby module. Apparently this is not what I am supposed to do. It appears that the point of a module is to store functions which can then be included as methods in a new class.

我不想要这个.我有一个类,我想将它保存在一个单独的文件中,我可以从其他文件中访问该文件.我该怎么做?

I don't want this. I have a class that I want to keep in a separate file which I can access from other files. How can I do this?

谢谢.

推荐答案

模块作为函数的持有者和命名空间具有双重用途.在模块中保留类是完全可以接受的.要将类放在单独的文件中,只需像往常一样定义类,然后在您希望使用该类的文件中,只需将 require 'name_of_file_with_class' 放在顶部.例如,如果我在 foo.rb 中定义了 class Foo,在 bar.rb 中我将有一行 require 'foo'.

Modules serve a dual purpose as a holder for functions and as a namespace. Keeping classes in modules is perfectly acceptable. To put a class in a separate file, just define the class as usual and then in the file where you wish to use the class, simply put require 'name_of_file_with_class' at the top. For instance, if I defined class Foo in foo.rb, in bar.rb I would have the line require 'foo'.

如果你使用 Rails,这个包含通常会自动发生

If you are using Rails, this include often happens automagically

文件布局的澄清

#file: foo.rb
class Foo
  def initialize
    puts "foo"
  end
end

...

#file: bar.rb
require 'foo'

Foo.new

如果您在 Rails 中,请将这些类放在 lib/ 中,并使用类名的小写下划线版本的文件的命名约定,例如Foo -> foo.rb, FooBar -> foo_bar.rb

If you are in Rails, put these classes in lib/ and use the naming convention for the files of lowercase underscored version of the class name, e.g. Foo -> foo.rb, FooBar -> foo_bar.rb, etc.

从 ruby​​ 1.9 版开始,您可以使用 require_relative 来要求相对于您正在编辑的文件的文件.

As of ruby version 1.9 you can use require_relative, to require files relatively to the file you are editing.

这篇关于从单独的文件中包含一个 Ruby 类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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