0

I have an app with this folder structure:

# /app/controllers/first_controller.
class FirstController
  def method
    'External'
  end
end

# /app/controllers/second_controller.rb
class SecondController
  def method
    'External'
  end
end

# /app/controllers/foo/first_controller.rb
module Foo
  class FirstController < ::FirstController
    def method
      'Internal'
    end
  end
end

My desidered behaviour is:

Foo::FirstController#method => "Internal"

Foo::SecondController#method => "External"

So, if the controller is not defined in the module Foo, it should instantiate the external cass

I tried creating a file foo.rb:

# /app/controllers/foo.rb
module Foo
  def self.const_missing(name)
    "::#{name}".constantize
  end
end

But using this makes rails ignore all the classes defined under /app/controllers/foo/*.rb (does not require them at all).

How can I obtain this?

geekdev
  • 1,192
  • 11
  • 15
ProGM
  • 6,949
  • 4
  • 33
  • 52

1 Answers1

1

Just let Rails to do the job if the class exists in Foo namespace. It uses const_missing to resolve the class names too:

module Foo
  def self.const_missing(name)
    if File.exists?("app/controllers/foo/#{name.to_s.underscore}.rb")
      super
    else
      "::#{name}".constantize
    end
  end
end

Output:

Foo::FirstController.new.method
# => "Internal" 
Foo::SecondController.new.method
# => "External" 
Oleg K.
  • 1,549
  • 8
  • 11