ruby modules and classes same name in structure - ruby-on-rails

I have a folder structure like the following in one of my projects:
lib
bar.rb
bar
other_bar.rb
another_bar.rb
next_bar.rb
...
bar.rb
require File.expand_path(File.dirname(__FILE__) + "/bar/other_bar.rb")
class Bar
puts "running BarBase"
end
bar/other_bar.rb
module Bar
class OtherBar
puts "running module Bar with class OtherBar"
end
end
If I now run ruby bar.rb I get this:
running module Bar with class OtherBar
bar.rb:3:in `': Bar is not a class (TypeError)
I'd like to have a similar structure to a rails model inheritance structure. How can I fix this? So far as I know ruby does not support this out of the box. Is there a workaround for such a situation?

Bar can't be a module and a class, they are different things.
Change bar.rb to module Bar or change other_bar.rb to class Bar.
Whichever it is, it has to be consistent. You can't change one to the other. The question is which should it be? If Bar is a container for other classes and only has a few global singleton methods? Then it's a module. But if it can be instantiated, then it's a class.
And yes, you can nest classes. This is totally acceptable:
class Bar
class OtherBar
puts "running module Bar with class OtherBar"
end
end
Bar::OtherBar.new # yay!
Modules and Classes can be nested inside either other in any way you see fit.
Edit with some commented examples to help clear this all up:
module Foo
# Foo::A
class A
# simple namespaced class
end
# Foo::B, inherits from Foo::A
class B < A
# inherting from a class in the same namespace
end
# modify Foo::B
class B
# When modifying an existing class you don't need to define the superclass
# again. It will raise an error if you reopen a class and define a different
# superclass. But leaving it off is fine.
end
# nested module Foo::Inner
module Inner
# Foo::Inner::C
class C
# simple more deeply namespaced class
end
# Foo::Inner::D, inherits from Foo::A
class D < A
# inherits from a class in a parent namespace
# works because ruby looks upward in the nesting chain to find missing constants.
end
# Foo::Inner::Foo
class Foo
# simple nested class with the same name as something in a parent namespace
# This is a totally different Foo, because it's in a different namespace
end
# Foo::Inner::E, inherits from Foo::Inner::Foo
class E < Foo
# class inhereting from another class in the same namespace
# Foo::Inner::Foo is "closer" than the global Foo, so that gets found as the superclass
end
# Foo::Inner::F, which mixes in the gloabl module Foo
class F
# the :: constant prefix says to start looking in the global namespace
# so here we include the top level module Foo, and not the "closer" in namespace Foo::Inner::Foo
include ::Foo
# This is an error. This attempts to include the class Foo::Inner::Foo since thats the closest by namespace
# thing that matches the constant Foo. (you can't include classes, only modules)
# You need the :: prefix to grab the global Foo module
include Foo
end
end
end
# Z decalred in the global namespace, which inherits from the deeply nested class Foo::Inner::C
class Z < Foo::Inner::C
# Any class anywhere can inherit from any other class in any namespace.
# Just drill in!
end
# the following 2 declarations at this point would be identical
# This defines a class deep with in a namespace
class Foo::Inner::Foo::Bar < Foo::A
end
# same as above, but reopens each namespace
module Foo
module Inner
class Foo
class Bar < ::Foo::A
end
end
end
end

Just use class Bar instead of module Bar. In Ruby, classes can be reopened and added to.

It is recommended not to use a class as a namespace, especially if you use Rails.
If you want to keep the Bar class in lib/bar.rb, an option is to move the other classes in the Bars namespace in lib/bars.rb.
Read more as to why here: https://blog.jetbrains.com/ruby/2017/03/why-you-should-not-use-a-class-as-a-namespace-in-rails-applications/
Update: this behavior is fixed in ruby 2.5
See: https://blog.bigbinary.com/2017/10/18/ruby-2.5-has-removed-top-level-constant-lookup.html

Related

Ambiguity in Ruby class name resolution

I recently did some code refactoring in a Rails codebase in which I converted some code that defined some classes like this (class bodies elided):
foo/user_bar.rb:
module Foo
class UserBar; end
end
foo/sub_user_bar.rb:
module Foo
class SubUserBar < UserBar; end
end
...to:
In foo/bar/user.rb:
module Foo
module Bar
class User; end
end
end
In foo/bar/sub_user.rb:
module Foo
module Bar
class SubUser < User; end
end
end
This introduced a subtle problem in that there was already an existing top-level class called User (a Rails model), and SubUser was being derived from that, not from User in the same module. I'm guess that this is because the order that Rails loads classes is unpredictable...?
Anyway, I found that I could disambiguate by declaring the SubUser class like this:
class SubUser < self::User
...which seems to work, although I couldn't find any examples of it in a modest amount of searching. It does look a little weird, though. And now I'm concerned that I really ought to be doing this for every class in my module, just in case a top-level class with the same name is ever introduced.
There are two styles of in-module class declarations throughout my company's codebase:
class A::B::Foo; end
And:
module A; module B; class Foo; end; end; end
I've always preferred the latter method since it allows for access to other names in the module without fully-qualified names, but now I've found that there's potentially a trap when I use it. So what's the best practice here?
Don't declare classes within a module; always use fully qualified names (class A::B::C::Foo < A::B::C::Bar)
Declare classes in a module but always fully qualify superclass names (module A; module B; module C; class Foo < A::B::C::Bar)
Declare classes in a module and use unqualified names but always use self:: when extending a class in the same module
Declare classes in a module and use unqualified names but stay aware of possible name collisions in the top-level namespace (seems risky)
Or do Ruby and/or Rails offer some other, cleaner way to resolve the issue?
Generally where there's ambiguity you specify full namespace paths:
module Foo
module Bar
class SubUser < Foo::Bar::User; end
end
end
That might seem verbose, but it's also specific and unambiguous.
Where you want to refer to literal top-level User you'd specify ::User.
Modules are identified by constants.1 The resolution of module look-ups is therefore determined by the procedure for looking up constant references. According to "The Ruby Programming Language", by David Flanagan and Yukihero Matsumoto, 1st Ed. 2008 (p. 261-262), constant look-ups are performed in the following order, where mod is the innermost module that encloses the reference to the constant:
mod.
the next enclosing module, continuing until there are no more enclosing modules. (Top-level/global constants are not considered at this step). The class method Module::nesting returns an array of modules that are so searched, in the order in which they are searched.
the elements of mod.ancestors, in index order (i.e., the inheritance hierarchy).
top-level constant definitions.
the value returned by the method Module#const_missing, with mod being the receiver and the constant expressed as a symbol being the argument, provided the method has been defined.
Let's see what we may learn by inserting puts Module.nesting.inspect and puts ancestors statements into the code.
module Foo
class UserBar
puts "nesting for UserBar=#{Module.nesting.inspect}"
puts "#{self}.ancestors=#{ancestors}"
end
end
# nesting for UserBar=[Foo::UserBar, Foo]
# Foo::UserBar.ancestors=[Foo::UserBar, Object, Kernel,
# BasicObject]
module Foo
class SubUserBar < UserBar
puts "nesting for SubUserBar=#{Module.nesting.inspect}"
puts "#{self}.ancestors=#{ancestors}"
end
end
# nesting for SubUserBar=[Foo::SubUserBar, Foo]
# Foo::SubUserBar.ancestors=[Foo::SubUserBar,
# Foo::UserBar, Object, Kernel, BasicObject]
module Foo
module Bar
class User
puts "nesting for User=#{Module.nesting.inspect}"
puts "#{self}.ancestors=#{ancestors}"
end
end
end
# nesting for User=[Foo::Bar::User, Foo::Bar, Foo]
# Foo::Bar::User.ancestors=[Foo::Bar::User, Object, Kernel,
# BasicObject]
module Foo
module Bar
class SubUser < User
puts "nesting for SubBar=#{Module.nesting.inspect}"
puts "#{self}.ancestors=#{ancestors}"
end
end
end
# nesting for SubBar=[Foo::Bar::SubUser, Foo::Bar, Foo]
# Foo::Bar::SubUser.ancestors=[Foo::Bar::SubUser,
# Foo::Bar::User, Object, Kernel, BasicObject]
This tells us that if there is a class User that is not contained within Foo (as in Rails), that class would the subject of references to User in the classes Foo::UserBar and Foo::SubUserBar, but not in Foo::Bar::User or Foo::Bar::SubUser. This understanding should help in organising modules to avoid namespace problems.
1 As classes are modules, whenever I reference "module" below I am referring to classes as well as modules that are not classes.

Ruby implicit inheritance of modules / classes

I defined one class SomeClass that includes methods with basic functionality. This class is defined in the Foo module.
# foo/
# |--some_class.rb
module Foo
class SomeClass
def some_method
puts "Hi!"
end
end
end
I also have two other modules: Bar and Baz. I want to include the entire namespacing of Foo inside of Bar and Baz, and inherit all methods defined under Foo, and thus to be able to overwrite Foo methods.
I also want to be able to overwrite this method only by specifying a new file in the right folder:
# baz/
# |--foo/
# |--some_class.rb
module Baz
module Foo
class SomeClass < ::Foo::SomeClass
def some_method
puts "Hey!"
end
end
end
end
This works fine. However, I want to be able to use Bar::Foo::SomeClass.some_method without having to create bar/foo/some_class.rb, and define empty modules and an empty SomeClass.
The same applies to inheritance of modules (by including).
Is there a way do accomplish this easily by using include, extend, or require, or something else? Since this is part of a Rails project (under the lib folder), can I use autoloading in a specific way?
The reason that I want to accomplish this is because I have many classes and modules with classes in it under Foo. The Bar and Baz modules should be able to inherit all modules/classes under Foo, and overwriting instance or class methods where it is needed by creating an explicit file. I would like to avoid creating a file for each class or module Foo has for Bar and Baz.
I have the following solution so far. I defined two new files: bar.rb and baz.rb. In bar.rb:
module Bar
def self.const_missing(name)
klass = Object.const_get(name.to_s) if name.to_s =~ /Foo/
return klass if klass
raise
rescue
super
end
end
> Bar
=> Bar # as expected
> Foo
=> Foo # as expected
> Bar::Foo
=> Foo # works!
> Bar::Foo::SomeClass
=> Foo::SomeClass # right
> Baz::Foo::SomeClass
=> Foo::SomeClass # not right...
I am not sure if I am on my way to a good solution now. Any feedback is highly appreciated.

Can a ruby class method inherit from another class?

I read here that a ruby class can only inherit from one class, and can include modules.
However, the devise module defines controllers like this:
class Users::PasswordsController < Devise::PasswordsController
...
end
Now, given that Users is probably a class, with PasswordsController being a method:
>> Devise::PasswordsController.class
=> Class
How is it that a method in a class inherits from another class?
class Users::PasswordsController < Devise::PasswordsController
...
end
In the above code, Users is the module and PasswordsController is the class inside Users module. Similarly Devise is the module and PasswordsController is the class inside Devise module.
so when you run
Users::PasswordsController.class
#=> Class
Users.class
#=>Module
What confuses you here is that you have wrong assumptions, namely:
Users is probably a class
Not necessarily. Here we have namespace with nesting, therefore Users can be either a class or a module. In fact classes are modules.
PasswordsController being a method
PasswordsController here is a class nested in the Users namespace. :: simply lets you go one level into the nesting tree.
Consider:
module Foo
class Bar
end
end
Foo::Bar.class # => class
From Rails naming convention, Users is most probably a module, and Users::PasswordsController is a class.
Note that :: is not for calling class methods (although it can be used this way). It's for accessing constants inside a module/class. For example
module Foo
BAR = 'bar'
end
Foo::BAR
#=> "bar"
In Ruby, a module/class name is a constant, and the value stored in it is the module/class. So :: also is used for accessing a module/class inside another module/class. For example
module Foo
class Bar
end
end
Foo::Bar
#=> Foo::Bar
Both Users and Device are modules, just used for scoping the real classes that are PasswordsController and PasswordsController.

What the difference between module and namespace for models

I have config in my application.rb for loading all models from subfolders:
config.autoload_paths += Dir["#{config.root}/app/models/**/"]
Lets assume, that I want to create model Bar in /models/foo/bar.rb
And now i can namespace the model Bar into folder Foo and name it like this:
class Foo::Bar
end
An opposite approach is to place it into module:
module Foo
class Bar
end
end
Name of the class from global namespace in both cases is the same.
Considering, that i do not need to include this module or include to this module, and made this only for placing models from one domain in namespace, what is the difference between these approaches?
One different is that your second example does not work if you also want to have a Foo class:
class Foo
end
module Foo
class Bar
end
end
# => TypeError: Foo is not a module
class Foo::Bar
end
# no error

inject/access methods from a parent module inside a model

In Rails I have the following structure
#.../models/A.rb
module A
def m
end
end
#.../models/a/B.rb
class A::B < ActiveRecord::Base
end
This automatically places A as a parent of B. Is there a way to do something like B.m without modifying B? I know that I could do something like B.parent.m and from there create aliases, but then i would have to change B.
I'm looking to somehow inject a code present in A into B, but I don't know where this automatic association is done behind the scenes.
Something like
module A
module C
def mc
end
end
def placed_as_parent (child) # supposing this is the method called to put this module as a parent
super child
child.include(C) #this is what I would like to do
end
end
The question behind it is that I have a module which is already being shared among several models of that folder and I would like to put some common stuff for the models in there without have to manually include/extend a module in each of my models
[[EDITED]]
I'm not being clear with my question. In rails 3 if you do
rails generate active_record:model A::B
it will generate the files
#.../models/A.rb
module A
def self.table_name_prefix
'a_'
end
end
#.../models/a/B.rb
class A::B < ActiveRecord::Base
end
So if I open a console and type
A::B.table_name # -> 'a_b'
A::B.table_name_prefix # -> ''
A::B.parent # -> A
A.table_name_prefix # 'a_'
This happens automatically without any include/extend in the model B. What I want is to include more stuff in A and access it from B, without changing anything on B as i described earlier.
To be honest I'm not sure I fully understand your question but I'll give it a shot anyway.
There is a hook in the Module class that allows you to get a reference to the class the module is being included into. Thus, you could then do virtually anything with it.
An example:
module A
# you can change the class' behavior here
def self.included(klass)
puts "included in #{klass}"
end
end
And then to use it:
class B
include A #this causes the included hook in the module to be called
end
Is this what you're after?
The OP wrote:
The question behind it is that I have a module which is already being shared among several models of that folder and I would like to put some common stuff for the models in there without have to manually include/extend a module in each of my models
Here's what I would do:
module Stuff1
...
end
module Stuff2
...
end
module StuffIWantInSeveralModels
include Stuff1, Stuff2
end
class X < ActiveRecord::Base
include StuffIWantInSeveralModels
end
class Y < ActiveRecord::Base
include StuffIWantInSeveralModels
end
Then when you want to add a new module to several of your models, you only have to write an "include" statement in one place (in the StuffIWantInSeveralModels module).
Each module should be in its own file in the lib directory, with the file name matching the name of the module so Rails auto-loading will work (e.g. stuff_i_want_in_several_models.rb).
Does this achieve what you wanted?

Resources