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

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!

Related

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 `min_cost' for ActiveModel::SecurePassword:Module

I am following Michale harlt's ruby on rails tutorial.Everything was going fine uptill I got stuck into this problem in which after giving user name and password and clicking on "Login" push button and I am getting an error "undefined method `min_cost' for ActiveModel::SecurePassword:Module".I am trying to resolve this issue from last 2 days but could'nt able to find any relevant solution.
Please help me to solve this.Thanks in advance.Here are all my relevant files of project. (I am using rails 3.2.16)
For any further information please let me know.
user.rb
class User < ActiveRecord::Base
attr_accessor :remember_token
before_save { self.email = email.downcase }
validates :name, presence: true, length: { maximum: 50 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+#[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true, length: { maximum: 255 },
format: { with: VALID_EMAIL_REGEX },
uniqueness: { case_sensitive: false }
has_secure_password
validates :password, length: { minimum: 6 }
# Returns the hash digest of the given string.
def User.digest(string)
cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST :
BCrypt::Engine.cost
BCrypt::Password.create(string, cost: cost)
end
# Returns a random token.
def User.new_token
SecureRandom.urlsafe_base64
end
# Remembers a user in the database for use in persistent sessions.
def remember
self.remember_token = User.new_token
update_attribute(:remember_digest, User.digest(remember_token))
end
# Returns true if the given token matches the digest.
def authenticated?(remember_token)
BCrypt::Password.new(remember_digest).is_password?(remember_token)
end
end
sessions_helper.rb
module SessionsHelper
# Logs in the given user.
def log_in(user)
session[:user_id] = user.id
end
# Remembers a user in a persistent session.
def remember(user)
user.remember
cookies.permanent.signed[:user_id] = user.id
cookies.permanent[:remember_token] = user.remember_token
end
# Returns the user corresponding to the remember token cookie.
def current_user
if (user_id = session[:user_id])
#current_user ||= User.find_by_id(user_id)
elsif (user_id = cookies.signed[:user_id])
user = User.find_by_id(user_id)
if user && user.authenticated?(cookies[:remember_token])
log_in user
#current_user = user
end
end
end
# Returns true if the user is logged in, false otherwise.
def logged_in?
!current_user.nil?
end
# Log Out Current User
def log_out
session.delete(:user_id)
#current_user = nil
end
end
sessions_controller.rb
class SessionsController < ApplicationController
def new
end
def create
user = User.find_by_email(params[:session][:email].downcase)
if user && user.authenticate(params[:session][:password])
log_in user
remember user
redirect_to user
else
flash.now[:danger] = 'Invalid email/password combination'
render 'new'
end
end
def destroy
log_out
redirect_to home_path
end
end
GemFile
source 'https://rubygems.org'
gem 'rails', '3.2.16'
gem 'bcrypt-ruby', '~> 3.1.2'
gem 'strong_parameters'
# Bundle edge Rails instead:
# gem 'rails', :git => 'git://github.com/rails/rails.git'
group :development, :test do
gem 'sqlite3', '1.3.9'
gem 'guard'
end
group :test do
gem 'minitest-reporters'
gem 'mini_backtrace', '0.1.3'
gem 'guard-minitest', '2.3.1'
end
group :production do
gem 'pg', '0.17.1'
gem 'rails_12factor', '0.0.2'
gem 'puma', '2.11.1'
end
# Gems used only for assets and not required
# in production environments by default.
group :assets do
gem 'coffee-rails', '~> 3.2.1'
gem 'sass-rails', '>= 3.2'
gem 'bootstrap-sass', '~> 3.3.4'
gem 'sprockets-rails', '=2.0.0.backport1'
gem 'sprockets', github: 'tessi/sprockets', branch: '2_2_2_backport2'
# See https://github.com/sstephenson/execjs#readme for more supported runtimes
# gem 'therubyracer', :platforms => :ruby
gem 'uglifier', '>= 1.0.3'
end
gem 'jquery-rails'
# To use ActiveModel has_secure_password
# gem 'bcrypt-ruby', '~> 3.0.0'
# To use Jbuilder templates for JSON
# gem 'jbuilder'
# Use unicorn as the app server
# gem 'unicorn'
# Deploy with Capistrano
# gem 'capistrano'
# To use debugger
# gem 'debugger'
Application Trace
app/models/user.rb:14:in `digest'
app/models/user.rb:27:in `remember'
app/helpers/sessions_helper.rb:10:in `remember'
app/controllers/sessions_controller.rb:10:in `create'
As far as I remember, SecurePassword#min_cost appeared in rails4 (or in rails3 > 3.2.16.)
Since you are just learning, my advice would be not to concentrate on solving this particular error, but just substitute the problematic line with:
cost = BCrypt::Engine::MIN_COST
or even with
cost = 10
and go further. Whether you are still to fix this, you should upgrade your rails up to 4 (or whatever version this method was introduced.)

getting wrong number argument error using Rails

Hi i am getting the following errors while using wicked_pdf gem in Rails3.
error:
ArgumentError in UsersController#download_pdf
wrong number of arguments (0 for 1)
Rails.root: C:/Site/generate4
Application Trace | Framework Trace | Full Trace
app/controllers/users_controller.rb:6:in `download_pdf'
After clicking on download pdf link the following error is coming.
error-2:
RuntimeError in UsersController#download_pdf
Error: Failed to execute:
["C:/Program Files/wkhtmltopdf/bin/wkhtmltopdf.exe", "--encoding", "UTF-8", "file://C:/DOCUME~1/SUBHRA~1/LOCALS~1/Temp/wicked_pdf20150527-1192-1qf0ac.html", "C:/DOCUME~1/SUBHRA~1/LOCALS~1/Temp/wicked_pdf_generated_file20150527-1192-fijfxt.pdf"]
Error: PDF could not be generated!
Command Error: Loading pages (1/6)
[> ] 0%
[======> ] 10%
Error: Failed loading page file://c/DOCUME~1/SUBHRA~1/LOCALS~1/Temp/wicked_pdf20150527-1192-1qf0ac.html (sometimes it will work just to ignore this error with --load-error-handling ignore)
Exit with code 1 due to network error: ContentNotFoundError
Please check my code below.
users_controller.rb:
class UsersController < ApplicationController
def index
end
def download_pdf
pdf=WickedPdf.new.pdf_from_string(
render_to_string pdf: "test.pdf", template: "users/test.html.erb", encoding: "UTF-8")
#save_path = 'C:\Site\download_pdf.pdf'
end
end
users/test.html.erb:
<h1>Hello rails</h1>
wicked_pdf.rb:
WickedPdf.config = {
#:wkhtmltopdf => '/usr/local/bin/wkhtmltopdf',
#:layout => "pdf.html",
:exe_path => 'C:/Program Files/wkhtmltopdf/bin/wkhtmltopdf.exe'
}
Gemfile:
source 'https://rubygems.org'
gem 'rails', '3.2.19'
gem 'sqlite3'
group :assets do
gem 'sass-rails', '~> 3.2.3'
gem 'coffee-rails', '~> 3.2.1'
gem 'uglifier', '>= 1.0.3'
end
gem 'jquery-rails'
gem 'wicked_pdf'
My requirement is convert HTML to PDF using Rails 3.Please help me to resolve this error and successfully get the PDF file.
Assuming, you are trying to download the pdf file.
see the code below:
#users_controller.rb:
class UsersController < ApplicationController
def download_pdf
pdf = render_to_string(pdf: "test.pdf", template: "users/test.html.erb", encoding: "UTF-8")
send_data pdf
end
end
# Gemfile
source 'https://rubygems.org'
gem 'rails', '3.2.19'
gem 'sqlite3'
group :assets do
gem 'sass-rails', '~> 3.2.3'
gem 'coffee-rails', '~> 3.2.1'
gem 'uglifier', '>= 1.0.3'
end
gem 'jquery-rails'
gem 'wicked_pdf', :github => 'mileszs/wicked_pdf', :branch => 'master'
Please check if it works.

Cannot get my Articles controller to create a blog Article with a picture. I am using imagemagick and carrierwave

My create action in ArticlesController seems fine if I create an Article without uploading a picture. However, if I try to upload a picture for an article, I get the error:
ActionController::UrlGenerationError in ArticlesController#create
No route matches {:action=>"show", :controller=>"articles", :id=>nil} missing required keys: [:id]
Here is my Articles controller:
class ArticlesController < ApplicationController
before_filter :require_login, only: [:new, :create, :edit, :update, :destroy]
def index
#articles = Article.all
end
def show
#article = Article.find(params[:id])
#comment = Comment.new
#comment.article_id = #article.id
end
def new
#article = Article.new
end
def create
#article = Article.new(article_params)
#article.save
redirect_to article_path(#article)
end
def edit
#article = Article.find(params[:id])
end
def destroy
#article = Article.find(params[:id])
#article.destroy
redirect_to articles_path
end
def update
#article = Article.find(params[:id])
#article.update(article_params)
flash.notice = "Article '#{#article.title}' Updated!"
redirect_to article_path(#article)
end
private
def article_params
params.require(:article).permit(:title, :body, :tag_list, :picture)
end
end
Here is my Article model:
class Article < ActiveRecord::Base
has_many :comments
has_many :taggings
has_many :tags, through: :taggings
mount_uploader :picture, PictureUploader
validate :picture_size
def tag_list
self.tags.collect do |tag|
tag.name
end.join(", ")
end
def tag_list=(tags_string)
tag_names = tags_string.split(",").collect{|s| s.strip.downcase}.uniq
new_or_found_tags = tag_names.collect { |name| Tag.find_or_create_by(name: name) }
self.tags = new_or_found_tags
end
# Validates the size of an uploaded picture.
def picture_size
if picture.size > 5.megabytes
errors.add(:picture, "should be less than 5MB")
end
end
end
My Gemfile :
source 'http://rubygems.org'
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.1.8'
# Use sqlite3 as the database for Active Record
gem 'sqlite3'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 4.0.3'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .js.coffee assets and views
gem 'coffee-rails', '~> 4.0.0'
# See https://github.com/sstephenson/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby
gem 'carrierwave', '0.10.0'
gem 'mini_magick', '~> 4.0.4'
gem 'fog', '~> 1.27.0'
# Use jquery as the JavaScript library
gem 'jquery-rails'
# Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks
gem 'turbolinks'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.0'
gem 'sorcery'
# bundle exec rake doc:rails generates the API under doc/api.
gem 'sdoc', '~> 0.4.0', group: :doc
# Use ActiveModel has_secure_password
gem 'bcrypt', '~> 3.1.7'
# Use unicorn as the app server
# gem 'unicorn'
# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development
# Use debugger
# gem 'debugger', group: [:development, :test]
# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin]
And finally my picture uploader:
# encoding: utf-8
class PictureUploader < CarrierWave::Uploader::Base
# Include RMagick or MiniMagick support:
# include CarrierWave::RMagick
include CarrierWave::MiniMagick
process resize_to_limit: [500, 500]
if Rails.env.production?
storage :fog
else
storage :file
end
# Override the directory where uploaded files will be stored.
# This is a sensible default for uploaders that are meant to be mounted:
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
# Provide a default URL as a default if there hasn't been a file uploaded:
# def default_url
# # For Rails 3.1+ asset pipeline compatibility:
# # ActionController::Base.helpers.asset_path("fallback/" + [version_name, "default.png"].compact.join('_'))
#
# "/images/fallback/" + [version_name, "default.png"].compact.join('_')
# end
# Process files as they are uploaded:
# process :scale => [200, 300]
#
# def scale(width, height)
# # do something
# end
# Create different versions of your uploaded files:
# version :thumb do
# process :resize_to_fit => [50, 50]
# end
# Add a white list of extensions which are allowed to be uploaded.
# For images you might use something like this:
def extension_white_list
%w(jpg jpeg gif png)
end
# Override the filename of the uploaded files:
# Avoid using model.id or version_name here, see uploader/store.rb for details.
# def filename
# "something.jpg" if original_filename
# end
end
What am I doing wrong with carrierwave and Imagemagic to get
this error ?

Command not found after installing jRuby gem

I am getting an issue trying to execute a command after installing a custom jRuby gem. In the gem I created, the Gemfile looks like below:
source "http://rubygems.org"
gem 'archive-tar-minitar', '~> 0.5.2'
gem 'fastercsv', '~> 1.5.4'
gem 'rake', '~> 0.9.2.2'
gem 'liquid', '>= 2.3.0'
gem 'net-sftp', '>=2.0.5'
gem 'net-ssh', '>=2.3.0'
gem 'jruby-openssl', '>=0.7.5'
gem 'crypt', '~>1.1.4'
gem 'nokogiri', '1.5.2'
and the .gemspec file:
$:.push File.expand_path("../lib", __FILE__)
require "example/version"
require "rake"
Gem::Specification.new do |s|
s.name = "example"
s.version = Example::VERSION
s.platform = 'java'
s.date = '2012-03-30'
s.executables = ["load_csv_to_table"]
s.rdoc_options = ["--charset=UTF-8"]
s.add_dependency('bundler', '~> 1.0')
s.add_dependency('archive-tar-minitar', '~> 0.5.2')
s.add_dependency('liquid', '>= 2.3.0')
s.add_dependency('net-sftp', '>=2.0.5')
s.add_dependency('net-ssh', '>=2.3.0')
s.add_dependency('jruby-openssl', '>=0.7.5')
s.add_dependency('crypt', '~>1.1.4')
s.add_dependency('fastercsv', '~> 1.5.4')
s.add_dependency('json', '~>1.6.6')
s.add_dependency('nokogiri', '1.5.2')
s.files = FileList['lib/**/*.rb', 'bin/*', 'vendor/java/**/*', 'resources/**/*'].to_a
s.require_path = ['lib']
s.required_rubygems_version = ">= 1.3.4"
end
In the bin folder, I created a command called 'example':
#!/usr/bin/env jruby
$:.unshift(File.dirname(__FILE__) + '/../lib') unless $:.include?(File.dirname(__FILE__) + '/../lib')
require 'example'
require 'pp'
pp "Example!!"
I installed the gem created in my local system with no errors (jruby -S gem install example-0.0.1-java.gem), but I when I try launch the command "example" the command doesn't seem to be found

Resources