简体   繁体   中英

Why am i getting Uninitialized constant error if class in subfolder in rails?

I'm having an odd issue that's haunting me. I have some custom classes defined in /lib/**/** that I'm trying to load in a controller. So given:


# dir: lib/forms/enums/data_type.rb
module Forms
  class DataType
    TEXT       = 0
    NUMBER     = 1
  end
end


# dir: controllers/form_controller.rb
class FormController < ApplicationController
  def update
   # Here, I get the uninitialized constant error for MyModule::DataType
   if params[:someAttr] ===  Forms::DataType::TEXT
    ...
   end
  ...
  end
...
end

However, if I place the DataType class in dir: lib/forms/ , ie in the same folder as forms , instead of the subfolder enums , it can reference it just fine.

I'm sure I'm doing something basic very wrong, but I don't understand why Rails can find any classes under modules, but not in subdirectories?

Update/Edit: It seems to work if I refer to it add it under an additional submodule, and refer to it as Forms::Enums::DataType::TEXT , like so:


# dir: lib/forms/enums/data_type.rb
module Forms
  module Enums
    class DataType
      TEXT       = 0
      NUMBER     = 1
    end
  end
end

So, if I introduce a subdirectory, is it required to always introduce a sub-module?

Looks like - As the comments to the question itself have pointed out,

  1. If I introduce a subdirectory, if you need it autoloaded, it seems that a sub-module is required.
  2. You can bypass this if you manually load a class

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM