Mongoid error in heroku: Database should be a Mongo::DB, not a nil class - ruby

I have a Sinatra app on heroku and it keeps crashing due to this error:
app/vendor/bundle/ruby/1.9.1/gems/mongoid-1.2.14/lib/mongoid/config.rb:52 in 'master': Database should be a Mongo::DB, not a nil class
I set up Mongoid 3.x according to the heroku instructions, and the app works on my local machine, so I'm not sure what's causing this problem. My gemfile looks like this:
source "https://rubygems.org"
ruby "1.9.3"
gem 'sinatra'
gem 'mongo'
gem 'mongoid'
gem 'bson_ext'
gem 'json'
gem 'nokogiri'
gem 'aws-s3', '0.6.2', :require => 'aws/s3'
gem 'sinatra-reloader'
gem 'debugger'
gem 'thin'
Here's my mongoid.yml:
development:
sessions:
default:
database: db
hosts:
- localhost:27017
production:
sessions:
default:
uri: <%= ENV['MONGOHQ_URL'] %>
options:
skip_version_check: true
safe: true
And here's my app file:
require 'bundler/setup'
require 'sinatra'
require 'json'
require 'mongo'
require 'mongoid'
Mongoid.load!('mongoid.yml', :production)
def get_connection
return #db_connection if #db_connection
db = URI.parse(ENV['MONGOHQ_URL'])
db_name = db.path.gsub(/^\//, '')
#db_connection = Mongo::Connection.new(db.host, db.port).db(db_name)
#db_connection.authenticate(db.user, db.password) unless (db.user.nil? || db.user.nil?)
#db_connection
end
db = get_connection
class Model1
include Mongoid::Document
field :name, :type => String
end
I shouldn't have to specify a database name since I'm using the uri field, so I'm not sure why the database if nil?

Related

Not sure why my rake seed file isn't running

here is my seed file :
require 'pry'
require 'rest-client'
require 'json'
require 'faker'
Consumer.delete_all
AlcoholicBeverage.delete_all
Intake.delete_all
100.times do
name = Faker::Name.first_name
sex= Faker::Gender.binary_type
weight= Faker::Number.between(from: 1, to: 10)
Consumer.create!(name:name,sex:sex,weight:weight)
end
ingredients=RestClient.get("https://raw.githubusercontent.com/teijo/iba-cocktails/master/recipes.json")
#ingredients_data=JSON.parse(ingredients)
#ingredients_data.collect do |x,y|
AlcoholicBeverage.create(cocktail_name: x["name"],glass: x["glass"],garnish: x["garnish"],preparation: x["preparation"])
end
100.times do
consumer_id = rand(1..100)
alcoholic_beverage_id = rand(1..100)
Intake.create!(consumer_id: consumer_id, alcoholic_beverage_id:alcoholic_beverage_id)
end
here is my gemfile:
# frozen_string_literal: true
source "https://rubygems.org"
gem "activerecord", '~> 5.2'
gem "sinatra-activerecord"
gem "sqlite3", '~> 1.3.6'
gem "pry"
gem "require_all"
gem "faker"
gem 'rest-client'
I've already ran my migrations fine.. so I'm not sure why nothing is showing up when I enter rake db:seed into my terminal.
Any advice or help will be much appreciated. I've also tried including require 'faker' in my seed file as well but it didn't change a thing.
This alternative approach will help you avoid missing data, by not depending on your ids being from 1 to 100:
consumers = 100.times.map do
name = Faker::Name.first_name
sex= Faker::Gender.binary_type
weight= Faker::Number.between(from: 1, to: 10)
Consumer.create!(name:name,sex:sex,weight:weight)
end
ingredients=RestClient.get("https://raw.githubusercontent.com/teijo/iba-cocktails/master/recipes.json")
#ingredients_data=JSON.parse(ingredients)
beverages = #ingredients_data.map do |x,y|
AlcoholicBeverage.create(cocktail_name: x["name"],glass: x["glass"],garnish: x["garnish"],preparation: x["preparation"])
end
100.times do
Intake.create!(consumer: consumers.shuffle.first, alcoholic_beverage: beverages.shuffle.first)
end

undefined method `namespace' for main:Object (NoMethodError) - active record / rakefile

I'm attempting to run a basic Sinatra app. When I get to the 'rackup' step I get an error:
/.rvm/gems/ruby-2.2.1/gems/activerecord-4.2.1/lib/active_record/railties/databases.rake:3:in `<top (required)>': undefined method `namespace' for main:Object (NoMethodError)
It seems to be a scope issue in the Rake gem. I've had no luck findding an answer and I'm not quite sure what needs to be fixed. I did update all my gems in hopes that would help to no avail. Here is my code that might be contributing....
rakefile.rb
require "./frank"
require "sinatra/activerecord/rake"
config.ru
require_relative 'frank'
map('/welcomes') { run WelcomesController }
frank.rb
require 'sinatra/base'
require 'active_record'
require 'bcrypt'
Dir.glob('./{controllers,models}/*rb').each { |file| require file }
ENV['SINATRA_ENV'] ||= 'development'
ActiveRecord::Base.establish_connection(
:adapter => 'sqlite3',
:database => "db/#{ENV['SINATRA_ENV']}.sqlite"
)
spec_helper.rb
ENV['SINATRA_ENV'] = 'test'
require_relative '../frank'
require 'capybara'
require 'database_cleaner'
Capybara.app = Rack::Builder.parse_file(File.expand_path('../../config.ru',__FILE__)).first
RSpec.configure do |config|
config.include Capybara::DSL
config.before(:suite) do
DatabaseCleaner.clean_with(:truncation)
end
config.before(:each) do
DatabaseCleaner.strategy = :transaction
end
config.before(:each) do
DatabaseCleaner.start
end
config.after(:each) do
DatabaseCleaner.clean
end
end
Many thanks :)
This is below the primary error:
from /Users/stephaniedean/.rvm/gems/ruby-2.2.1/gems/sinatra-activerecord-2.0.6/lib/sinatra/activerecord/rake.rb:1:in `load'
from /Users/stephaniedean/.rvm/gems/ruby-2.2.1/gems/sinatra-activerecord-2.0.6/lib/sinatra/activerecord/rake.rb:1:in `<top (required)>'
So, it looks like sinatra-activerecord not just activerecord. I did try activerecord 3.2.17 that didn't work. Thanks for the suggestions.
this took up hours of my time before I found the solution:
http://aaronlerch.github.io/blog/sinatra-bundler-and-the-global-namespace/
https://github.com/sinatra/sinatra-contrib/issues/111
Gemfile
gem "sinatra", require: 'sinatra/base'
gem 'sinatra-activerecord', require: false
gem 'sinatra-contrib', require: false
Environment.rb
require 'bundler/setup'
require 'rake'
require 'sinatra'
require 'sinatra/reloader'
require 'sinatra/activerecord'
require 'sinatra/activerecord/rake'
make sure to
require 'rake'
before
require 'sinatra/activerecord/rake'

Adapter not set: default. Did you forget to setup?

I'm getting the same error when I execute my test in Rspec. DataMapper::RepositoryNotSetupError: Adapter not set: default. Did you forget to setup? I don't understand this error because I've set up Datamapper as it says in Datamapper webpage. I show you my code
vip_client-spec.rb
require 'spec_helper'
require 'data_mapper'
require 'dm-postgres-adapter'
require File.join(File.dirname(__FILE__), '..', '..', 'models', 'vip_client.rb')
describe VipClient do
before {
DataMapper.finalize.auto_upgrade!
}
describe "#insert_into_database" do
it "inserts clients into database from an array of hashes" do
list_clients = [
{name: "David", birthday: "13-12-1985", email: "daviddsrperiodismo#gmail.com"},
{name: "Javier", birthday: "05-05-1985", email: "javier#gmail.com"}
]
VipClient.insert_into_database(list_clients)
expect(VipClient.all.count).to eq(2)
end
end
end
vip_client.rb
class VipClient
include ::DataMapper::Resource
property :id, Serial
property :name, Text
property :birthday, Date
property :email, Text
def self.insert_into_database(list_clients)
end
end
app.rb
require 'sinatra'
require 'data_mapper'
require 'roo'
require 'pony'
# HELPERS
require './helpers/code'
require './helpers/check_birthday_users'
require './helpers/excel_parser'
# MODELS
require './models/vip_client.rb'
require './models/invitations.rb'
include Code
include CheckUsers
DataMapper.setup(:default, 'postgres://david:123456#localhost/usersmareta')
DataMapper.finalize.auto_upgrade!
And my gemfile is this
source "https://rubygems.org"
gem 'sinatra'
gem 'pg'
gem 'roo'
gem 'data_mapper'
gem 'dm-postgres-adapter'
gem 'pony'
group :development, :test do
gem 'rack-test'
gem 'rspec'
end
As I've said. when I do rspec the console gives me this:
Failure/Error: DataMapper.finalize.auto_upgrade!
DataMapper::RepositoryNotSetupError:
Adapter not set: default. Did you forget to setup?

Sinatra with Postgres and ActiveRecord | Error Pushing to Heroku is: Invalid DATABASE_URL

I have an application written in Sinatra that works locally but that I cannot seem to push up to heroku.
When I attempt to push to heroku I get the following error:
-----> Writing config/database.yml to read from DATABASE_URL
Could not detect rake tasks
ensure you can run $ bundle exec rake -P against your app with no environment variables present
and using the production group of your Gemfile.
This may be intentional, if you expected rake tasks to be run
cancel the build (CTRL+C) and fix the error then commit the fix:
rake aborted!
Invalid DATABASE_URL
My Gemfile
source 'https://rubygems.org'
ruby '2.0.0'
gem 'sinatra', require: 'sinatra/base'
gem "pg"
gem "activerecord"
gem "sinatra-activerecord"
gem "rake"
gem 'minitest', require: false
gem 'rack-test', require: false
gem 'faraday'
gem 'json'
gem 'minitest-reporters'
My database.yml file
development:
adapter: postgresql
encoding: unicode
database: calendar_development
host: localhost
password:
test:
adapter: postgresql
encoding: unicode
database: calendar_test
pool: 5
host: localhost
password:
My config.ru
require './app'
run Sinatra::Application
ENV['RACK_ENV'] ||= 'development'
Procfile
web: bundle exec rackup config.ru -p $PORT
Rakefile
require "sinatra/activerecord/rake"
require 'rake/testtask'
require "./app"
task :default => :test
env = ENV["SINATRA_ENV"] || "development"
Rake::TestTask.new do |t|
t.libs << 'test'
t.test_files = FileList["test/**/*_test.rb"]
t.verbose = false
end
The app.rb
require 'sinatra'
require 'sinatra/activerecord'
require 'json'
Dir[File.dirname(__FILE__) + '/models/*.rb'].each {|file| require file }
env_index = ARGV.index("-e")
env_arg = ARGV[env_index + 1] if env_index
env = env_arg || ENV["SINATRA_ENV"] || "development"
use ActiveRecord::ConnectionAdapters::ConnectionManagement # close connection to the DDBB properly...https://github.com/puma/puma/issues/59
databases = YAML.load_file("config/database.yml")
ActiveRecord::Base.establish_connection(databases[env])
if env == 'test'
User.destroy_all
end
I removed all the environment test from my app.rb file and moved it to environments:
app.rb
require './config/environments'
Then I changed the DB setup - first of all, removed all the ENV[SINATRA_ENV]
environments.rb
configure :production, :development, :test do
db = URI.parse(ENV['DATABASE_URL'] || 'postgres://localhost/calendar_development')
ActiveRecord::Base.establish_connection(
:adapter => db.scheme == 'postgres' ? 'postgresql' : db.scheme,
:host => db.host,
:username => db.user,
:password => db.password,
:database => db.path[1..-1],
:encoding => 'utf8'
)
end
I changed my Rakefile
namespace :db do
task :seed do
seed_file = File.join('db/seeds.rb')
load(seed_file) if File.exist?(seed_file)
end
end
I followed sybohy's advice and in my config.ru file, I removed the last line - leaving
config.ru
require './app'
run Sinatra::Application
I ran:
heroku addons | grep POSTGRES
grabbed the name of the db (HEROKU_POSTGRESQL_JADE)
heroku pg:reset HEROKU_POSTGRESQL_JADE
and then migrated
heroku run rake db:migrate
So far this seems to have fixed the errors! I will update if I find more!

Unable to make a rake-tasks file and make it work properly

I decided to create a rake tasks for my Sinatra project and not to use the ready ones.
#Rakefile
require 'rake/testtask'
require 'rake/clean'
Dir.glob("tasks/*.rake").each { |r| import r }
#/tasks/seed.rake
require 'rubygems'
require 'bundler'
Bundler.require
require 'mongoid'
require_relative '../models/user'
namespace :db do
task :seed do
puts 'Creating a user....'
user1 = User.new email: "email1#gmail.com", password: "test123"
user1.save!
puts 'User has been created.'
end
end
#user.rb
require 'bcrypt'
require 'digest/md5'
require 'openssl'
class User
include Mongoid::Document
include Mongoid::Timestamps
#.........
#gemfile (partly)
source 'http://rubygems.org'
gem 'bcrypt-ruby', require: 'bcrypt'
And I've got the error of "Creating a user....
rake aborted!
undefined method `create!' for BCrypt::Password:Class
/home/alex/ruby_projects/service/models/user.rb:47:in `password='"
where #47 looks like
def password= pass
self.hashed_password = BCrypt::Password.create! pass, cost: 10
end
Note that in normal development everything works just fine. So I missed to require a file I think.
Your thoughts?
p.s. Even if I put
require 'bcrypt'
require 'digest/md5'
require 'openssl
to /tasks/seed.rake the error remains.
It appears you are using a non-existant method from BCrypt::Password. According to the docs, there is only a .create method and no .create! method. Switch to BCrypt::Password.create and it should work.
def password= pass
self.hashed_password = BCrypt::Password.create pass, cost: 10
end

Resources