包含来自单独文件的Ruby类 [英] Including a Ruby class from a separate file

查看:56
本文介绍了包含来自单独文件的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中定义了类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.rbFooBar-> 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天全站免登陆