Rails NameError uninitialized constant class solution

rails nameerror uninitialized constant class will occur if your rails console is not loaded with configuration of the class file containing method being called.

Problem

Basically this can happen if you happened to call the function from the class which is not loaded with configuration when your rails console/server was started.

Example

Suppose you create a file named Util.rb in the lib folder of your Rails project.

Class Util
   def self.get_date
	Time.now.strftime(‘%F’)
   end
end

And then if you want to call the function through command line i.e. rails console probably you will start rails console and and call the method get_date using class name Util as follows,

rails console
> Util.get_date

This will give you following error -
NameError: uninitialized constant Util
It means that your class was not loaded when the rails console was started

Solution

To resolve this problem your class has to be loaded in environment, this can be done in following way,

1. Open application.rb file of your Rails project
2. Add following line in application.rb

config.autoload_paths += %W(#{config.root}/lib)

Your application.rb will look something like,

require File.expand_path(‘../boot‘, __FILE__)
require ‘rails/all‘

# Require the gems listed in Gemfile, including any gems
# you‘ve limited to :test, :development, or :production.
Bundler.require(:default, Rails.env)

module RubyInRailsApp
  class Application < Rails::Application
    # the new line added for autoload of lib
    config.autoload_paths += %W(#{config.root}/lib)

    # Settings in config/environments/* take precedence over those specified here.
    # Application configuration should go into files in config/initializers
    # -- all .rb files in that directory are automatically loaded.

    # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
    # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
    # config.time_zone = ‘Central Time (US & Canada)‘

    # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
    # config.i18n.load_path += Dir[Rails.root.join(‘my‘, ‘locales‘, ‘*.{rb,yml}‘).to_s]
    # config.i18n.default_locale = :de
  end
end

3. Done

Conclusion

Thus, Setting autoload_paths for config in application.rb will result for - ruby files present in lib directory of your Rails project to get automatically loaded when your console is started. Calling method will not give rails nameerror uninitialized constant class error anymore.
Now, calling the method -

Util.get_date

will return result as expected. As the class was loaded with configuration when your console was started thus Name resolution was successful.

Ultimately these kind of errors can be reduced if you configure your Rails application properly. ReadConfiguring Rails application to know more about configurations.

Rails NameError uninitialized constant class solution,布布扣,bubuko.com

时间: 2024-12-15 01:39:48

Rails NameError uninitialized constant class solution的相关文章

解决脱离rails使用activerecord报错 NameError: uninitialized constant ActiveRecord::Migrator::Zlib

上下文说明 原本系统是15.10,无奈只支持1年,所以今天升级16.04,环境答好后运行rake migratte报错 1 task :default => :migrate 2 3 desc 'Run migrations' 4 task :migrate do 5 6 ActiveRecord::Migrator.migrate('db/migrate', ENV['VERSION'] ? ENV['VERSION'].to_i : nil) 7 end NameError: uniniti

redmine安装code review遇到的错误 uninitialized constant Redmineapp

给redmine1.2.1,安装code review插件时执行 rake db:migrate_plugins RAILS_ENV=production 遇到这个错误uninitialized constant Redmineapp,经过不断的查找是因为code review 的版本下载错了,得用code review 0.4.4,最后重新安装则成功

第一个Ruby程序报错 uninitialized constant Hello

今天是我第一次接触Ruby语言,按照教程编写了一个很简单的Ruby程序,将文件命名为Hello.rb,内容如下: puts "Hello,Ruby!"; 但是执行时却报错: 百度后的解决方案如下:你还在irb里面,所以报这个错,你退出(exit)irb,然后执行ruby Hello.rb就可以了. 我尝试退出irb,但是程序自动进入irb#1,执行还是报错: 我打开cmd执行ruby C:\Ruby22\bin\Hello.rb命令后可以正常输出: 另外,在写puts语句的时候,后面的

刻意练习--Rails RESTful(一)

一本被人反复提及的书<哪儿来的天才>中说过,大部分所谓的天才都是通过反复的刻意练习得到的.当你的练习时间达到10000小时以后,你就会成为该领域的专家. 最近在学习rails如何实现RESTful Web Service.自己想给自己设计一个练习的模板,进行反复练习.开发过程采用的是TDD的方式进行开发. 练习背景: 我们涉及三个Domain对象,Products.Orders.Payment 1.新建工程rails-rest-practice rails new rails-rest-pra

有意练习--Rails RESTful(一)

书要反复提及<哪里有天才>在说,大多数所谓的天才是通过反复刻意练习获得. 当你的练习时间达到10000几个小时后,.你将成为该领域的专家. 近期在学习rails怎样实现RESTful Web Service. 自己想给自己设计一个练习的模板,进行重复练习. 开发过程採用的是TDD的方式进行开发. 练习背景: 我们涉及三个Domain对象,Products.Orders.Payment 1.新建projectrails-rest-practice rails new rails-rest-pra

渗透杂记-2013-07-12

[email protected]:~# msfpro [*] Starting Metasploit Console... [-] WARNING! The following modules could not be loaded! [-] /opt/metasploit/apps/pro/msf3/modules/exploits/freebsd/local/mmap.rb: NameError uninitialized constant Msf::Post::Common Call t

kali Linux系列教程之BeFF安装与集成Metasploit

kali Linux系列教程之BeFF安装与集成Metasploit 文/玄魂 1.1 apt-get安装方式 1.2 启动 1.3 基本测试 1.4 异常信息 1.5 从源码安装BeEF 1.5.1 安装curl git 1.5.2 安装rvm 1.5.3 安装依赖项 1.5.4 安装ruby 1.5.5 安装bundler 1.5.6下载beef 1.5.7 安装和启动 1.6 集成metasploit 1.1 apt-get安装方式 打开终端,输入如下命令: apt-get install

编译的 Ruby 2.3.0 缺少 openssl 支持的解决方法 (已解决)

我的系统是centos 7.5,已离线安装ruby-2.3.0,openssl-1.0.2l,rubygems-2.7.4 如下图: 但是在  gem sources -a http://gems.ruby-china.org/   时报错 Unable to require openssl, install OpenSSL and rebuild ruby (preferred) or use non-HTTPS sources 重新编译发现, make的输出中有 configuring op

rails tutorial sample app

阅读第3章时,按照教程第一次运行rspec失败了: E:\05 Create\Code\temp\railstutorial\sample_app>rspec spec/requests/static_pages_spec.rbE:/05 Create/Code/temp/railstutorial/sample_app/spec/spec_helper.rb:32:in `block (2 levels) in <top (required)>': uninitialized cons