How do you create hierarchical class names in Ruby?

In Ruby, a class called Foo will be defined using class Foo , which will be used through require 'foo' and will live in $:[0]/foo.rb or something like that.

But what about Foo::Bar ? Will this be called with require 'foo/bar' ? Will he live in $:[0]/foo/bar.rb ? And how will it be determined?

I’m very used to Perl, where for personal projects I would make nested classes such as Project::User , Project::Text::Index , Project::Text::Search , etc. Then I would make a file of type Project/Text/Index.pm , which would start with package Project::Text::Index and be called through use Project::Text::Index; .

Now I am starting a project in Ruby and have no idea how to do this. For some reason, not one of the Ruby books or documents I read about mentions perl-style hierarchy class names. When they mention inheritance, it's usually through a trivial example like class Foo < Bar , which doesn't really help me. However, I suppose it should be possible to do what I'm trying because Rails (just take one example) has classes like ActionView::Helpers::ActiveModelFormBuilder .

+4
source share
2 answers

Here you combine several concepts that are not really related, namely: the boot path, inheritance, and the region resolution operator.

When requesting (or downloading) files, the argument of the require keyword is simply taken as the path to the file and added to the download search path (the .rb extension is optional for require ). Inheritance and nesting don't come into play here, and any file can define everything it wants, for example:

 require 'foo' # Looks for "foo.rb" in each of $: require 'foo/bar' # Looks for "foo/bar.rb" in each of $: 

Nested classes (and modules, variables, etc.) are defined as expected, but are resolved using the scope resolution operator, for example:

 class Foo def foo; 'foo'; end class Bar def bar; 'bar'; end end end Foo.new.foo # => "foo" Foo::Bar.new.bar # => "bar" 

Note that nesting and inheriting classes are not related to the location of the file from which they are loaded. It seems that there are no explicit conventions for structuring classes and modules, so you can do what works for you. The Ruby Language page of the Ruby programming page can also be useful.

+6
source

You need modules. If you need a class identified by Funthing::Text::Index in Funthing/Text/Index.rb and required with require 'Funthing/Text/Index' , you do this:

 # file Funthing/Text/Index.rb module Funthing module Text class Index def do_the_twist() puts "Let twist again!" end end end end 

Then use it as follows:

 require "Funthing/Text/Index" c = Funthing::Text::Index.new 

Note. The file hierarchy is not , but (in my opinion) is best practice.

+3
source

Source: https://habr.com/ru/post/1338653/


All Articles