using custom classes in rails console - ruby-on-rails

I create a custom class which I call MyClass in a module MyModule
module MyModule
class MyClass
def initialize
... # Some code here
end
end
end
I save this code in a file called mymodule.rb
I place this file in the lib directory of my rails application, and add the following line to my application.rb
config.autoload_paths += %W(#{config.root}/lib)
When I fire up the rails console and try to use this file. it just doesnt work.
m = MyModule::MyClass.new()
NameError: uninitialized constant MyModule
from (irb):1
from /Users/matt/.rvm/gems/ruby-1.9.2-p0/gems/railties-3.0.6/lib/rails/commands/console.rb:44:in `start'
from /Users/matt/.rvm/gems/ruby-1.9.2-p0/gems/railties-3.0.6/lib/rails/commands/console.rb:8:in `start'
from /Users/matt/.rvm/gems/ruby-1.9.2-p0/gems/railties-3.0.6/lib/rails/commands.rb:23:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'
What do I need to do in order to be able to use that class in the rails console
Any help appreciated

Name the file my_class.rb and place it in the directory my_module. That should fix your problem.

Related

Heroku ActionController::RoutingError (uninitialized constant error)

Rails 4.2.4, Ruby 2.1.7
I have a module inside lib/ directory.
lib/BLL/user_feed.rb
module BLL
class UserFeed
def initialize
logger.debug "Class has been initialized"
end
def get_user_feed(user_id)
# logic here
return {
# object
}
end
end
end
When I try to include that in my controller to use my user_Feed logic,
class UserfeedController < ApplicationController
include BLL
before_action :authenticate_user!
def show
# some logic
end
end
In my config/application.rb
config.autoload_paths << Rails.root.join('lib')
This runs fine locally, however, it breaks when I deploy it on Heroku.
it's throwing
ActionController::RoutingError (uninitialized constant UserfeedController::BLL):
error.
2015-10-20T13:45:13.791457+00:00 app[web.1]: /app/app/controllers/api/v1/userfeed_controller.rb:1:in `<top (required)>': uninitialized constant Bll (NameError)
2015-10-20T13:45:13.791457+00:00 app[web.1]: from /app/vendor/bundle/ruby/2.1.0/gems/railties-4.2.4/lib/rails/engine.rb:472:in `block (2 levels) in eager_load!'
2015-10-20T13:45:13.791458+00:00 app[web.1]: from /app/vendor/bundle/ruby/2.1.0/gems/railties-4.2.4/lib/rails/engine.rb:471:in `each'
2015-10-20T13:45:13.791459+00:00 app[web.1]: from /app/vendor/bundle/ruby/2.1.0/gems/railties-4.2.4/lib/rails/engine.rb:471:in `block in eager_load!'
2015-10-20T13:45:13.791460+00:00 app[web.1]: from /app/vendor/bundle/ruby/2.1.0/gems/railties-4.2.4/lib/rails/engine.rb:469:in `each'
2015-10-20T13:45:13.791462+00:00 app[web.1]: from /app/vendor/bundle/ruby/2.1.0/gems/railties-4.2.4/lib/rails/engine.rb:469:in `eager_load!'
2015-10-20T13:45:13.791463+00:00 app[web.1]: from /app/vendor/bundle/ruby/2.1.0/gems/railties-4.2.4/lib/rails/engine.rb:346:in `eager_load!'
Any suggestions?
I think you're missing a module BLL; end in lib/bll.rb
But also, play with naming the module Bll, but I don't think that's it
try
config.autoload_paths += %W(#{config.root}/lib/BLL)
and dont forget to restart the server
Edit1
Moreover; changing the name of Dir BLL to bll also works
Ruby defaults to CamelCase, you'll have to use the following:
#vendor/bll/user_feed.rb
module Bll
class UserFeed
...
end
end
As a second, the vendor dir is autoloaded (to the best of my knowledge), so the above code should work to fix the UnrecognizedConstant error.
https://softwareengineering.stackexchange.com/questions/123305/what-is-the-difference-between-the-lib-and-vendor-folders
Rails in fact loads your app directory when the app loads. So actually no need to mention your app/bll in autoload paths.
However, what I am doing wrong here in this case is adding module on top of the class.
So, my app is looking for app/bll/bll/Whatever
module Bll - there is not need for this module to be declared
class Whatever
# some logic.
end
end
All you need to do is.
class Whatever
end
After this, your class is available to use.

Using a non-ActiveRecord model, can't access it through rails console

(Rails 4.2.4) Hello, beginner here. I am working on a project which does not need a DB or activeRecord. Therefore, when making my Rails project I appended the -O (to disable Active Record and database) (rails new MyApp -O)
I read that to do a model not backed by a database you can just create a file in
app/models/site.rb.
No need to do:
rails generate model Site
So I added my model, which looks something like this:
class Site
attr_reader :name
attr_reader :out_average
attr_reader :in_average
attr_reader :change
def initialize(name, in_average, out_average)
#name = name
#out_average = out_average
#in_average = in_average
#change = find_increase
end
def find_increase()
if #in_average && #out_average != 0
#change = ((#in_average - #out_average)/#out_average)*100
else
#change = 0
end
return #change
end
end
So, I then started up console "rails c" and when I try to invoke a new Site object, I get an error:
irb(main):001:0> Site.new
NameError: uninitialized constant Site
from (irb):1
from /home/ms-87/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/railties-4.2.4/lib/rails/commands/console.rb:110:in `start'
from /home/ms-87/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/railties-4.2.4/lib/rails/commands/console.rb:9:in `start'
from /home/ms-87/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/railties-4.2.4/lib/rails/commands/commands_tasks.rb:68:in `console'
from /home/ms-87/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/railties-4.2.4/lib/rails/commands/commands_tasks.rb:39:in `run_command!'
from /home/ms-87/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/railties-4.2.4/lib/rails/commands.rb:17:in `<top (required)>'
from /home/ms-87/Documents/projects/rails_projects/site_seasonality/bin/rails:8:in `<top (required)>'
from /home/ms-87/.rbenv/versions/2.2.3/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require'
from /home/ms-87/.rbenv/versions/2.2.3/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require'
from -e:1:in `<main>'
I made sure I started the console from the root of my app. I also made sure to use the proper naming convention (site.rb is the filename in app/model/, "Site" is the name of my class inside the file). Can anyone help me as to why this isn't working? Is my thinking here wrong? Thanks.
My first error was that my filenames were capitalized "Site.rb", I had actually fixed this before I posted. But after I fixed it, I accidentally started using "irb" instead of "rails c". DOH! Sorry for the post.

Testing code in a Rails engine with RSpec

I'm trying to do something seemingly simple but it's proven rather hard.
I want to write tests using RSpec for classes that I've put in the lib directory of a Rails Engine.
Here are exactly the steps I'm using:
rails plugin new mygem -T --mountable --full --dummy-path=spec/dummy
Then I cd mygem; vim mygem.gemspec
I add the following line to mygem.gemspec:
s.add_development_dependency "rspec-rails"
I run bundle install; rails generate rspec:install
Then I edit ~/mygem/lib/mygem/engine.rb adding the following:
module Mygem
class Engine < ::Rails::Engine
isolate_namespace Mygem
config.generators do |g|
g.test_framework :rspec
end
end
end
I create a very simple class in the lib directory, ~/mygem/lib/mygem/something.rb
and add the following:
module Mygem
class Something
def hi
"hi"
end
end
end
Create a test file ~/mygem/spec/something_spec.rb
then add the following:
require 'rails_helper'
describe Mygem::Something do
it 'says hi' do
s = Mygem::Something.new
expect(s.hi).to eq('hi')
end
end
And boom, I get the following output:
rspec
~/Documents/mygem/spec/rails_helper.rb:3:in `require': cannot load such file -- ~/Documents/mygem/config/environment (LoadError)
from ~/Documents/mygem/spec/rails_helper.rb:3:in `<top (required)>'
from ~/Documents/mygem/spec/something_spec.rb:1:in `require'
from ~/Documents/mygem/spec/something_spec.rb:1:in `<top (required)>'
from ~/.rvm/gems/ruby-2.2.2/gems/rspec-core-3.3.2/lib/rspec/core/configuration.rb:1327:in `load' from ~/.rvm/gems/ruby-2.2.2/gems/rspec-core-3.3.2/lib/rspec/core/configuration.rb:1327:in `block in load_spec_files'
from ~/.rvm/gems/ruby-2.2.2/gems/rspec-core-3.3.2/lib/rspec/core/configuration.rb:1325:in `each'
from ~/.rvm/gems/ruby-2.2.2/gems/rspec-core-3.3.2/lib/rspec/core/configuration.rb:1325:in `load_spec_files'
from ~/.rvm/gems/ruby-2.2.2/gems/rspec-core-3.3.2/lib/rspec/core/runner.rb:102:in `setup'
from ~/.rvm/gems/ruby-2.2.2/gems/rspec-core-3.3.2/lib/rspec/core/runner.rb:88:in `run'
from ~/.rvm/gems/ruby-2.2.2/gems/rspec-core-3.3.2/lib/rspec/core/runner.rb:73:in `run'
from ~/.rvm/gems/ruby-2.2.2/gems/rspec-core-3.3.2/lib/rspec/core/runner.rb:41:in `invoke'
from ~/.rvm/gems/ruby-2.2.2/gems/rspec-core-3.3.2/exe/rspec:4:in `<top (required)>'
from ~/.rvm/gems/ruby-2.2.2/bin/rspec:23:in `load'
from ~/.rvm/gems/ruby-2.2.2/bin/rspec:23:in `<main>'
from ~/.rvm/gems/ruby-2.2.2/bin/ruby_executable_hooks:15:in `eval'
from ~/.rvm/gems/ruby-2.2.2/bin/ruby_executable_hooks:15:in `<main>'
Any tips as to what I may be doing incorrectly?
Thanks in advance!
It looks like your rails_helper is looking for an environment.rb file to load, which doesn't exist in a Rails engine. It does, however, exist in your dummy app, which is what RSpec is run against.
Try adding this into the top of your rails_helper file:
require File.expand_path("../dummy/config/environment.rb", __FILE__)
Finally got it working after the following steps (thanks ccai for the suggestion):
in rails_helper.rb:
# Comment this line:
# require File.expand_path('../../config/environment', __FILE__)
require File.expand_path("../dummy/config/environment.rb", __FILE__)
then in lib/mygem.rb
require "mygem/something"
Works!

Creating generators Rails

I am having a problem creating a generator in rails this is the error I am getting.
I am trying to create a generator that creates does SMS verification through the provider Twilio.
require "sms_auth-twilio"
NameError: uninitialized constant Twilio::Rails
from /Users/sherodtaylor/.rvm/gems/ruby-1.9.3-p125/gems/sms_auth-twilio-0.0.2/lib/sms_auth-twilio.rb:3:in `<module:Twilio>'
from /Users/sherodtaylor/.rvm/gems/ruby-1.9.3-p125/gems/sms_auth-twilio-0.0.2/lib/sms_auth-twilio.rb:2:in `<top (required)>'
from /Users/sherodtaylor/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:60:in `require'
from /Users/sherodtaylor/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:60:in `rescue in require'
from /Users/sherodtaylor/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:35:in `require'
from (irb):1
from /Users/sherodtaylor/.rvm/rubies/ruby-1.9.3-p125/bin/irb:16:in `<main>'
This is my code
require "sms_auth-twilio/version"
module Twilio
class TwilioGenerator < Rails::Generator::Base
source_root File.expand_path("../generator", __FILE__)
def add_twilio_initializer
copy_file "twilio.rb", "config/initializer/twilio.rb"
end
# config info for the API
def twilio_config_info
copy_file "twilio.yml", "config/twilio.yml"
end
# Verification Controller to verify the company
def copy_verifications
copy_file "verifications_controller", "app/contoller/verifications_controller.rb"
end
end
end
Restarting your Rails server and then try
For your Help see this link : Rails Adding Twilio Sub Accounts : Uninitialized constant User::Twilio
I can't say for sure, but this is not typically how I see generators created within a gem. Usually they are separate from the actual gem_name.rb file. I think if you move the generator logic into the more common lib/generators/generator_name/generator_name.rb you'll have more luck. And then you can place the files to be copied within a subdir ../generator_name/templates/
Also note you need to add the .rb ending to your copy_file "verifications_controller,"
For a template to work off, you can follow the layout of a simple gem I wrote here which utilizes a generator.

Rails 3: How to include files from "lib" directory when running tests?

When I run:
ruby -I test test/unit/job_test.rb
from the application root directory, I got the following error:
.../app/models/name_position.rb:9:in `<class:NamePosition>':
uninitialized constant NamePosition::PositionManager (NameError)
from .../app/models/name_position.rb:1:in `<top (required)>'
from .../app/models/ac_buyer.rb:1:in `<top (required)>'
...
Here is the relevant code:
# app/models/ac_buyer.rb
class AcBuyer < NamePosition
end
# app/models/name_position.rb
class NamePosition < ActiveRecord::Base
...
include PositionManager
end
# lib/position_manager.rb
module PositionManager
...
end
It looks like when running tests, the files from the lib directory are not loaded automatically.
Any suggestions ?
Try putting this in your application.rb
config.autoload_paths += %W(#{config.root}/lib)

Resources