Red
Red

Reputation: 2246

Model namespace issue in rails

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.

Upvotes: 1

Views: 1017

Answers (1)

Behrang Saeedzadeh
Behrang Saeedzadeh

Reputation: 47971

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.

Upvotes: 3

Related Questions