Sinatra, Mongoid ActiveRecord::AdapterNotSpecified: database configuration does not specify adapter - ruby

I am trying to create a create_indexes rake task for creating indexes for MongoDb records in my application.
I have Rakefile in the top directory of my application, with the following code.
require "./app"
set :database_file, "./config/mongoid.yml"
Dir.glob('lib/tasks/*.rake').each { |r| load r}
I have create a db.rake file in the lib/tasks folder in my app
namespace :db do
task :create_indexes => :environment do
#
begin
Rails.application.eager_load!
rescue Object => e
end
#
begin
Bundler.require(:default, :assets, 'production')
rescue Object => e
end
#
to_index_models = []
ObjectSpace.each_object(Module) do |object|
begin
to_index_models.push(object) if object.respond_to?(:create_indexes)
rescue Object => e
warn "failed on: #{ object }.respond_to?(:create_indexes)"
end
end
#
to_index_models.sort! do |a, b|
begin
a.name <=> b.name
rescue Object
0
end
end
#
begin
to_index_models.uniq!
rescue Object
end
#
to_index_models.each do |model|
begin
model.create_indexes
puts "indexed: #{ model }"
rescue Object => e
warn "failed on: #{ model }#create_indexes"
end
end
end
end
This was taken from http://grokbase.com/t/gg/mongoid/12akaq1na7/equivalent-of-create-indexes-rake-task-in-non-rails-environment#20121106gzwpoiifznpdxa3ugtzdvjgplq
And my mongoid.yml file is a basic connection to localhost file:
development:
sessions:
default:
database: mongoid
hosts:
- localhost:27017
But whenever I am trying to run the rake task as:
rake db:create_indexes[development]
I am getting the following error:
rake aborted!
ActiveRecord::AdapterNotSpecified: database configuration does not specify adapter
/Users/harshsingh/.rvm/gems/ruby-2.1.2/gems/activerecord-4.2. 0/lib/active_record/connection_adapters/connection_specification.rb:171:in `spec'
/Users/harshsingh/.rvm/gems/ruby-2.1.2/gems/activerecord-4.2.0/lib/active_record/connection_handling.rb:50:in `establish_connection'
/Users/harshsingh/.rvm/gems/ruby-2.1.2/gems/sinatra-activerecord-2.0.4/lib/sinatra/activerecord.rb:39:in `database='
/Users/harshsingh/.rvm/gems/ruby-2.1.2/gems/sinatra-1.4.5/lib/sinatra/base.rb:1208:in `set'
/Users/harshsingh/.rvm/gems/ruby-2.1.2/gems/sinatra-activerecord-2.0.4/lib/sinatra/activerecord.rb:33:in `database_file='
/Users/harshsingh/.rvm/gems/ruby-2.1.2/gems/sinatra-1.4.5/lib/sinatra/base.rb:1208:in `set'
/Users/harshsingh/.rvm/gems/ruby-2.1.2/gems/sinatra-1.4.5/lib/sinatra/base.rb:1982:in `block (2 levels) in delegate'
/Users/harshsingh/Documents/Codes/mogreet-requestbin/Rakefile:2:in `<top (required)>'
/Users/harshsingh/.rvm/gems/ruby-2.1.2/bin/ruby_executable_hooks:15:in `eval'
/Users/harshsingh/.rvm/gems/ruby-2.1.2/bin/ruby_executable_hooks:15:in `<main>'
(See full trace by running task with --trace)

Related

How can I force Rspec to not falsely think another module is nested inside the parent?

I have an issue that's appearing only when running rspec, my application loads and works fine locally and in production
rspec seems to think that the gem JWT belongs to my module BACKBONE
An error occurred while loading spec_helper.
Failure/Error: JWT.encode(payload, ENV['APP_SECRET'], 'HS256')
NameError:
uninitialized constant BACKBONE::JWT
# ./lib/jwt.rb:6:in `encode'
# ./lib/backbone/policies.rb:7:in `<class:Policy>'
# ./lib/backbone/policies.rb:5:in `<module:BACKBONE>'
# ./lib/backbone/policies.rb:3:in `<top (required)>'
# ./init.rb:10:in `load'
# ./init.rb:10:in `block in <module:CrewManagement>'
# ./init.rb:10:in `glob'
# ./init.rb:10:in `<module:CrewManagement>'
# ./init.rb:4:in `<top (required)>'
# ./spec/spec_helper.rb:16:in `require'
# ./spec/spec_helper.rb:16:in `<top (required)>'
files are listed in the order they are loaded into memory, it may be useful to note that I have several other applications with the same setup that are not experiencing this issue
/spec/spec_helper.rb
require 'bundler'
require 'simplecov'
SimpleCov.start
Bundler.require :default
Dotenv.load("./.env.#{(ENV['RACK_ENV'] || 'development')}")
require 'rack/test'
require './init'
# ...
/init.rb
module CrewManagement
## ...
Dir.glob('./lib/**/*.rb') { |file| load file }
## ...
end
/lib/jwt.rb
module BACKBONE
def self.encode(payload)
JWT.encode(payload, ENV['APP_SECRET'], 'HS256')
end
def self.decode(token)
JWT.decode(token, ENV['APP_SECRET'], true, algorithm: 'HS256')
end
end
/lib/backbone/policies.rb
module BACKBONE
headers = { 'Authorization' => BACKBONE.encode(app: '...') }
end

Mongoid and Rspec error Mongo::Error::NoServerAvailable:

When I am starting my Rspec test, I get this error:
1) User checks if the user is created
Failure/Error: expect{ #user_test = create(:user) }.to change { User.count }
Mongo::Error::NoServerAvailable:
No server is available matching preference: #<Mongo::ServerSelector::Primary:0x70316515164800 tag_sets=[] max_staleness=nil> using server_selection_timeout=30 and local_threshold=0.015
# /Users/aliceguillaume/.rvm/gems/ruby-2.3.4/gems/mongo-2.5.0/lib/mongo/server_selector/selectable.rb:115:in `select_server'
# /Users/aliceguillaume/.rvm/gems/ruby-2.3.4/gems/mongo-2.5.0/lib/mongo/collection/view/readable.rb:139:in `block in count'
# /Users/aliceguillaume/.rvm/gems/ruby-2.3.4/gems/mongo-2.5.0/lib/mongo/retryable.rb:44:in `read_with_retry'
# /Users/aliceguillaume/.rvm/gems/ruby-2.3.4/gems/mongo-2.5.0/lib/mongo/collection/view/readable.rb:138:in `count'
# /Users/aliceguillaume/.rvm/gems/ruby-2.3.4/gems/mongoid-5.2.1/lib/mongoid/contextual/mongo.rb:70:in `block in count'
# /Users/aliceguillaume/.rvm/gems/ruby-2.3.4/gems/mongoid-5.2.1/lib/mongoid/contextual/mongo.rb:504:in `try_cache'
# /Users/aliceguillaume/.rvm/gems/ruby-2.3.4/gems/mongoid-5.2.1/lib/mongoid/contextual/mongo.rb:70:in `count'
# /Users/aliceguillaume/.rvm/gems/ruby-2.3.4/gems/mongoid-5.2.1/lib/mongoid/contextual.rb:20:in `count'
# /Users/aliceguillaume/.rvm/gems/ruby-2.3.4/gems/mongoid-5.2.1/lib/mongoid/findable.rb:55:in `count'
# ./spec/models/user_spec.rb:11:in `block (3 levels) in <top (required)>'
# ./spec/models/user_spec.rb:11:in `block (2 levels) in <top (required)>'
Finished in 30.14 seconds (files took 8.39 seconds to load)
1 example, 1 failure
Failed examples:
rspec ./spec/models/user_spec.rb:10 # User checks if the user is created
I am really confused about it.
My mongo server is running too.
My user_spec.rb:
require 'spec_helper'
require 'rails_helper'
require 'database_cleaner'
DatabaseCleaner.strategy = :truncation
RSpec.describe User, :type => :model do
it "checks if the user is created" do
expect{ #user_test = create(:user) }.to change { User.count }
end
end
Any idea why my mongo won't work?
Found the answer
My config file had mistake so I change it to :
test:
clients:
default:
database: test
hosts:
- 127.0.0.1:27017
options:
read:
mode: :primary
max_pool_size: 1
log_level: :debug

Overwriting 'require' leads to "no such file to load

I deleted my original post, because I can now simplify my question with a very short program:
## a.rb
require 'tmpdir'
Executing a.rb is fine, no error.
But if I overwrite require as:
## b.rb
module Kernel
alias_method :original_require, :require
def require name
i = 1
begin
original_require name
rescue LoadError => e
puts "Failure #{i}: #{e}"
i = i + 1
retry if i < 3
end
end
end
require 'tmpdir'
Executing b.rb will get the following error:
Failure 1: no such file to load -- Win32API
Failure 2: no such file to load -- Win32API
/Users/chaol/.rvm/rubies/ruby-1.9.1-p376/lib/ruby/1.9.1/tmpdir.rb:19:in `<class:Dir>': uninitialized constant Dir::Win32API (NameError)
from /Users/chaol/.rvm/rubies/ruby-1.9.1-p376/lib/ruby/1.9.1/tmpdir.rb:9:in `<top (required)>'
from /Users/chaol/Documents/ruby-workspace/Test/root/aaa.rb:9:in `require'
from /Users/chaol/Documents/ruby-workspace/Test/root/aaa.rb:9:in `require'
from /Users/chaol/Documents/ruby-workspace/Test/root/aaa.rb:20:in `<main>'

rake spec failed, it cannot load or find constant or global variable

I create standalone rspec test script to testing existing api framework. It works pretty well, but I found problem where in the Rakefile I need to assign some value from YAML file (uri link, email) either CONSTANT or $global_var the code in the Rakefile looks like this:
require 'rubygems'
require 'bundler/setup'
require 'yaml'
require 'rspec/core/rake_task'
task :default => :spec
desc 'Running rspec test'
task :spec, :option do |t, opt|
choice = opt[:choice]
if choice == "production"
puts 'Test running on production'
VAR = YAML::load(File.read(File.expand_path("../config/prod_variable.yml", __FILE__)))
elsif choice == "development"
puts 'Test running on development'
VAR = YAML::load(File.read(File.expand_path("../config/dev_variable.yml", __FILE__)))
end
puts VAR['URI'] #=> print out the value correctly
RSpec::Core::RakeTask.new do |task|
test = Rake.application.original_dir
task.fail_on_error = false
task.rspec_opts = '--format documentation --color'
end
end
When I run the rake command on the terminal, the rspec failed find the VAR constant value. Here is the error message from rspec
Failures:
1) ApiTest Testing API platform for GET request
Failure/Error: #var = ApiTest.new(VAR['URI'] ,
NameError:
uninitialized constant VAR
# ./rspec_test/api_test/api_test_get_spec.rb:8:in `block (2 levels) in <top (required)>'
2) ApiTest Testing API platform for POST request
Failure/Error: #zat = ApiTest.new(VAR['URI'] ,
NameError:
uninitialized constant VAR
# ./rspec_test/api_test/api_test_post_spec.rb:7:in `block (2 levels) in <top (required)>'
Is there any idea how to get this works? I need to get value from VAR constant or global variable, but seems ruby failed to assign the value.
If opt[:choice] is neither "production" nor "development", VAR is undefined in your code.

Rake task not running

Every time I call my rake task it say:
[2012-07-12 15:50:01] ERROR IOError: An existing connection was forcibly closed by the remote host
C:/jruby-1.3.1/lib/ruby/1.8/webrick/httpresponse.rb:324:in `_write_data'
C:/jruby-1.3.1/lib/ruby/1.8/webrick/httpresponse.rb:180:in `send_header'
C:/jruby-1.3.1/lib/ruby/1.8/webrick/httpresponse.rb:103:in `send_response'
C:/jruby-1.3.1/lib/ruby/1.8/webrick/httpserver.rb:79:in `run'
C:/jruby-1.3.1/lib/ruby/1.8/webrick/server.rb:173:in `start_thread'
C:/jruby-1.3.1/lib/ruby/1.8/webrick/server.rb:162:in `start'
[2012-07-12 15:50:29] ERROR IOError: An existing connection was forcibly closed by the remote host
C:/jruby-1.3.1/lib/ruby/1.8/webrick/httpserver.rb:55:in `run'
C:/jruby-1.3.1/lib/ruby/1.8/webrick/server.rb:173:in `start_thread'
C:/jruby-1.3.1/lib/ruby/1.8/webrick/server.rb:162:in `start'
I have tryed different options thinking that it could be the call to the rake task but apparently isn't, also I have tryed with Mongrel and WEBRick in case that it could be the server.
I'm using Jruby 1.3.1
The task it's not been executed.
This is part of my code:
application_controller.rb
def call_rake(task, options = {})
options[:rails_env] ||= Rails.env
args = options.map { |n, v| "#{n.to_s.upcase}='#{v}'" }
system "C:/jruby-1.3.1/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake #{task} #{args.join(' ')} start"
end
forbidden_file.rake
desc "Process CSV file"
task :process_file => :environment do
forbidden_file = ForbiddenFile.find(ENV["csv"])
forbidden_file.upload_file
end
Controller
...
call_rake :process_file, :csv => params[:files]
redirect_to forbidden_files_url
...
It's working now, I just removed the word start from the command.
system "rake #{task} #{args.join(' ')}"

Resources