Not sure why my rake seed file isn't running - ruby

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

Related

How do I merge two or more results from elasticsearch rails gem?

I'm trying to merge two elasticsearch results into one variable, here my code tries...
class SearchController < ApplicationController
def index
end
def advanced
#results = {}
if !params[:fast_search].empty?
#results[:features] = TestCases.search(params[:fast_search]).results
#results[:steps] = Steps.search(params[:fast_search]).results
#results[:examples] = Examples.search(params[:fast_search]).results
else
unless params[:feature].blank?
features = TestCases.search(query: { match: { function: params[:feature] } }).results
features_tag = Steps.search(query: { match: { tags: params[:tags] } }).results
#results[:features] = features + features_tag
end
unless params[:steps].blank? || params[:scenario].blank?
#results[:steps] = Steps.search(query: { match: { scenario: params[:scenario] } }).results
params[:steps].each do |step|
#results[:steps] += Steps.search(query: { match: { steps: step } }).results
end
#results[:steps] += Steps.search(query: { match: { tags: params[:tags] } }).results
end
unless params[:examples].blank?
params[:examples].each do |example|
#results[:examples] += Examples.search(query: { match: { examples: example } }).results
end
#results[:examples] += Examples.search(query: { match: { tags: params[:tags] } }).results
end
unless params[:bug].blank?
#results[:miscs] = StepsMiscs.search(query: { match: { bug: true } }).results
end
end
render "search/index"
end
end
I also try features.merge(features_tag) but no success either.
It's simple, I just need to merge one and more results from the elasticsearch, but I simply don't know how.
Here's my Gemfile:
source 'https://rubygems.org'
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 5.0.0', '>= 5.0.0.1'
# Use sqlite3 as the database for Active Record
gem 'sqlite3'
# Use Puma as the app server
gem 'puma', '~> 3.0'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.2'
# See https://github.com/rails/execjs#readme for more supported runtimes
gem 'therubyracer', platforms: :ruby
# Use jquery as the JavaScript library
gem 'jquery-rails'
# Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks
gem 'turbolinks', '~> 5'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.5'
# Use Redis adapter to run Action Cable in production
# gem 'redis', '~> 3.0'
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'
# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development
# jQuery-Turbolinks
gem 'jquery-turbolinks'
# Mysql
gem 'mysql2'
# Safe Attributes
gem 'safe_attributes'
# Elastic Search
gem 'elasticsearch-model'
gem 'elasticsearch-rails'
gem 'elasticsearch-persistence'
gem 'pry'
#rake
gem 'rake'
#sidekiq
gem 'sidekiq'
group :development, :test do
# Call 'byebug' anywhere in the code to stop execution and get a debugger console
gem 'byebug', platform: :mri
end
group :development do
# Access an IRB console on exception pages or by using <%= console %> anywhere in the code.
gem 'web-console'
end
group :production do
#passenger
gem "passenger", require: "phusion_passenger/rack_handler"
end
# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]
And here's obviously the error that I'm getting:
undefined method `+' for #<Elasticsearch::Model::Response::Results:0x0000000d2719f8>
Thanks!
Here after a lot of search, I've found this:
unless params[:steps].blank? || params[:scenario].blank? || params[:tags].blank?
query = Jbuilder.encode do |json|
json.query do
json.match do
json.scenario do
json.query params[:scenario]
end
end
params[:steps].each do |step|
json.match do
json.tags do
json.query step
end
end
end
json.match do
json.tags do
json.query params[:tags]
end
end
end
end
#results[:steps] = Steps.search(query).results
end
This help me to search more than one match on all my models.
I know that catch only the basics, but at the moment is part for what I need and I hope this could help all the others around here with the same issue!
Thanks you all!

Ruby: Strange string comparison assertion behaviour

Can anyone explain what is happening here? I have this simple class with some static methods, and I want to test them.
yaqueline/build/converters/asciidocconverter.rb
# encoding: UTF-8
require 'asciidoctor'
module Yaqueline
module Build
module Converters
class AsciiDocConverter < Converter
class << self
def matches path
path =~ /\.(asciidoc|adoc|ascii|ad)$/
end
def convert content
html = Asciidoctor.convert content, to_file: false, safe: :safe
html = get_guts_out_of_body html
puts "asciidoc #{html}"
html
end
def get_guts_out_of_body html
if html =~ /<body>/
puts "get guts: #{html}"
return html.match(%r{(?<=<body>).*(?=</body>)})
end
html
end
end # class << self
end # class
end
end
end
and the test in test/build/converters/asciidocconverter_test.rb:
# encoding: utf-8
require 'helper'
require 'yaqueline/build/converters/asciidocconverter'
class TestAsciidocConverter < Test::Unit::TestCase
should "be able to get body html from a document" do
value = %q{SUCCESS}
html = %Q{
<html>
<head>
<title>Hej värld</title>
</head>
<body>#{value}</body>
</html>}
guts = Yaqueline::Build::Converters::AsciiDocConverter.get_guts_out_of_body html
puts "guts was '#{guts}'"
assert value.eql?(guts), "guts was '#{guts}', expected '#{value}'"
end
end
When running the test with
$ rake test TEST=test/build/converters/asciidocconverter_test.rb
The results looks good to me:
Started
get guts:
<html>
<head>
<title>Hej värld</title>
</head>
<body>SUCCESS</body>
</html>
guts was 'SUCCESS'
F
===============================================================================================================================================================================
Failure:
guts was 'SUCCESS', expected 'SUCCESS'.
<false> is not true.
test: AsciidocConverter should be able to get body html from a document. (TestAsciidocConverter)
/Users/mats/src/examples/yaqueline/test/build/converters/asciidocconverter_test.rb:37:in `block in <class:TestAsciidocConverter>'
/Users/mats/src/examples/yaqueline/test/build/converters/asciidocconverter_test.rb:39:in `instance_exec'
/Users/mats/src/examples/yaqueline/test/build/converters/asciidocconverter_test.rb:39:in `block in create_test_from_should_hash'
===============================================================================================================================================================================
but the assertion fails which seems odd to me and I'll need some help.
I'm running ruby 2.4.1p111 (2017-03-22 revision 58053) [x86_64-darwin15]
and my Gemfilelooks like
# Add dependencies required to use your gem here.
# Example:
# gem "activesupport", ">= 2.3.5"
gem 'mercenary'
gem 'safe_yaml'
gem 'kramdown'
gem 'colorator'
gem 'pathutil'
gem 'nokogiri'
gem 'sass'
gem 'listen', '~> 3.0'
gem 'asciidoctor'
gem 'tilt'
gem 'erubis'
# Add dependencies to develop your gem here.
# Include everything needed to run rake, tests, features, etc.
group :development do
gem "rdoc", "~> 3.12"
gem "bundler", "~> 1.0"
gem "juwelier", "~> 2.1.0"
gem "simplecov", ">= 0"
gem 'rubocop', '~> 0.48.1', require: false
gem 'thin' # or whatever I end up with
gem 'minitest'
gem 'test-unit'
gem 'shoulda'
end
Maybe this helps to realize hat test harness I'm using.
Can anyone see the mistake or explain what's going on?
Cheers
Inspect the types of values being compared. One of them is not a string. (Thus, it can't be equal to a string).
guts = html.match(%r{(?<=<body>).*(?=</body>)})
guts # => #<MatchData "SUCCESS">
guts.to_s # => "SUCCESS"

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?

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

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?

Resources