Model namespace issue in rails

1k Views Asked by At

I am having an issue with namespaces in Rails 3.1. I have a class, let's call it a.

#/app/models/a.rb
class a
  #some methods
  def self.method_from_a
    #does things
  end
end

But I also have another class that has the same name in a different namespace.

#/app/models/b/a.rb
class b::a
  def method
    return a.method_from_a
  end
end

When I call b::a.method though I get:

NameError: uninitialized constant b::a::a

I am sure it is a simple solution, I am just missing it.

1

There are 1 best solutions below

1
On BEST ANSWER

Prefix a with :::

class b::a
  def method
    return ::a.method_from_a
  end
end

This, (i.e. the scope operator) is also explained here:

Constants defined within a class or module may be accessed unadorned anywhere within the class or module. Outside the class or module, they may be accessed using the scope operator, ::'' prefixed by an expression that returns the appropriate class or module object. Constants defined outside any class or module may be accessed unadorned or by using the scope operator::'' with no prefix.

By the way, in Ruby class names should start with an upper case letter.