简体   繁体   中英

Ruby on Rails require doesn't work?

It's my first RoR application.

I want to use this class (app/models/from_db/users/user_base.rb)

module FromDb::Users
  class UserBase
      include ActiveModel::Serializers::JSON

      attr_accessor :Login, :Email
 end
end

In this controller (app/controllers/my_controller.rb)

class MyController < ApplicationController
  require "from_db/users/user_base"

  def default
    user = UserBase.new
    user.Login = "Marcin"
    user.Email = "ja@gmail.com"
  end
end

user = UserBase.new throw this error:

uninitialized constant MyController::UserBase

When I put FromDb::Users::UserBase.new everything works fine but I thought that 'require' is like 'using' in C# or 'import' in java. I don't want to have to put this namespace all time before class from other dir. What I am doing wrong?

My second question. Is any way to write require "FromDb/Users/UserBase" instand of require "from_db/users/user_base" ? Now when I put first version (FromDb/Users/UserBase) it throw that error:

cannot load such file -- FromDb/Users/UserBase

I use ruby 2.1.5 and Rails 4.2.1

With regards to the first question, try the following to import the namespace

include FromDb::Users

Don't use imports all over the place as they might cause conflicts within your class (see comment by apneadiving).

Or simply create an alias:

FUsers = FromDb::Users
FUsers::UserBase.new...

While require is similar to Java's import , it doesn't have any of the namespace manipulation stuff that import provides. If you really want to have shorter references, you'll need to create them yourself.

class MyController < ApplicationController
  UserBase = FromDb::Users::UserBase

  def default
    user = UserBase.new
    # ... etc
  end
end

Also, since this is a Rails application, you don't need the explicit call to require (and it's better if you leave it off). If you name everything following the standard conventions, Rails will require the file for you automatically, then reload it whenever the file changes. If you do a manual require you'll lose the autoreloading.

require just loads file's content in memory, so you still have to use FromDb::Users::UserBase and I recommend it, its clearer.

You cant camelize the name: its is meant to be a file name.

You have to give the path from the root, its safer:

require "#{Rails.root}/app/models/from_db/users/user_base"

Notice you dont need require since you have your code in /app


in order to create a shortcut you could do:

def default
  user = user_base_class.new
end

def user_base_class
  ::FromDb::Users::UserBase
end

this way you dont create useless constant.

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