Sunday, October 16, 2016

Rails Rspec Capybara Selenium JS create not showing after pressing submit | Fixed issues

Rails Rspec Capybara Selenium JS create not showing after pressing submit | Fixed issues


Rails Rspec Capybara Selenium JS create not showing after pressing submit

Posted: 16 Oct 2016 07:33 AM PDT

I am building a web shop, the functionality is already there, namely: in ONE screen there is a list of products and a list of ordered items. When in a product pressing order, this product then shows up immediately in this list.

As you can guess, when wanting to do this with a test, using selenium I see Firefox starting up, I think I even see the button being pressed, but then obviously nothing happens. No item in my order list.

Using Rails 5 with an updated capybara and selenium webdriver.

  gem 'rspec-rails', '~> 3.5', '>= 3.5.1'    gem 'capybara', '~> 2.10', '>= 2.10.1'    gem "factory_girl_rails", "~> 4.7"    gem 'selenium-webdriver', '~> 3.0'    gem 'database_cleaner', '~> 1.5', '>= 1.5.3'      gem "email_spec", "~> 1.6.0"  

creating_order_spec.rb

require 'rails_helper'    RSpec.feature 'User can fill his shopping cart', js: true do    let!(:category) { FactoryGirl.create(:category, name: 'Honey') }    let!(:cheap_product) { FactoryGirl.create(:product, name: 'Honey lolly',                                                         price: '0,80',                                                        category: category) }    let!(:expensive_product) { FactoryGirl.create(:product, name: 'Honeyjar 400ml',                                                         price: '3,95',                                                        category: category) }      before do      visit categories_path    end      scenario 'with different products' do      page.find('#product', :text => 'Propolis lollie').click_button('VOEG TOE AAN MANDJE')      page.find('#product', :text => 'Honingpot 400ml').click_button('VOEG TOE AAN MANDJE')        within('#order') do        expect(page).to have_content 'Honey lolly'        expect(page).to have_content 'Honeyjar 400ml'        expect(page).to have_content 0.80 + 3.95      end    end  end  

Database_cleaning.rb

RSpec.configure do |config|      config.before(:suite) do      DatabaseCleaner.clean_with(:truncation)    end      config.before(:each) do      DatabaseCleaner.strategy = :transaction    end      config.use_transactional_fixtures = false      config.before(:each, :js => true) do      DatabaseCleaner.strategy = :truncation    end          config.before(:each) do      DatabaseCleaner.start    end      config.after(:each) do      DatabaseCleaner.clean    end  end  

Rails Multi-step form

Posted: 16 Oct 2016 07:07 AM PDT

I'm writing a quiz app with rails 5. I have got a multi-step form for question building.

Models:

class Mcq < ApplicationRecord    attr_accessor :option_count    has_many :options, dependent: :destroy    belongs_to :quiz      accepts_nested_attributes_for :options    validates :question_text, presence: true  end    class Option < ApplicationRecord    belongs_to :mcq, optional: true    validates :option_text, presence: true  end  

Schema:

create_table "mcqs", force: :cascade do |t|    t.string   "question_text"    t.boolean  "required"    t.boolean  "multiselect"    t.integer  "quiz_id"    t.datetime "created_at",    null: false    t.datetime "updated_at",    null: false  end      create_table "options", force: :cascade do |t|    t.string   "option_text"    t.integer  "mcq_id"    t.datetime "created_at",  null: false    t.datetime "updated_at",  null: false  end  

The first page is for question setup and has the following fields:

  1. Option Count
  2. Required (Yes / No)
  3. No of options that can be selected (Single / Multiple)

The second page is for options and has the following fields:

  1. Question Text
  2. Nested Form for Options

Controller:

class McqsController < ApplicationController    def new      session[:current_step] ||= 'setup'      session[:mcq_params] ||= {}        @current_step = session[:current_step]      @quiz = Quiz.find(params[:quiz_id])      @mcq = Mcq.new(session[:mcq_params])        if session[:current_step] == 'options'        @option_count = session[:mcq_params]['option_count']        @option_count.times { @mcq.options.build }      end    end      def create      if params[:previous_button]        session[:current_step] = 'setup'        redirect_to new_quiz_mcq_path      elsif session[:current_step] == 'setup'        save_session(params[:mcq])        redirect_to new_quiz_mcq_path      elsif session[:current_step] == 'options'        @mcq = Mcq.new(whitelisted_mcq_params)        @mcq.quiz_id = params[:quiz_id]        @quiz = Quiz.find(params[:quiz_id])        if @mcq.save          session[:current_step] = session[:mcq_params] = nil          redirect_to quiz_new_question_path(@mcq.quiz_id)        else          @current_step = session[:current_step]          render :new        end      end    end      private      def whitelisted_mcq_params      params.require(:mcq)          .permit(:question_text, :multiselect, :required,    options_attributes: [:option_text])    end      def save_session(mcq_params)       session[:mcq_params][:option_count] = mcq_params[:option_count].to_i       session[:mcq_params][:required] = mcq_params[:required]       session[:mcq_params][:multiselect] = mcq_params[:multiselect]       session[:current_step] = 'options'    end  end  

The above solution works, but the code is messy and difficult to understand. I came across this railscasts episode which does something similar in a cleaner way. I've updated my code as follows:

class Mcq < ApplicationRecord    has_many :options, dependent: :destroy    belongs_to :quiz      attr_writer :current_step    attr_accessor :option_count      accepts_nested_attributes_for :options    validates :question_text, presence: true      def current_step      @current_step || steps.first    end      def steps      %w[setup options]    end      def next_step      self.current_step = steps[steps.index(current_step)+1]    end      def previous_step      self.current_step = steps[steps.index(current_step)-1]    end      def last_step?      current_step == steps.last    end  end    class McqsController < ApplicationController    def new      session[:mcq_params] ||= {}      @quiz = Quiz.find(params[:quiz_id])      @mcq = Mcq.new(session[:mcq_params])      @mcq.current_step = session[:mcq_step]    end      def create      @quiz = Quiz.find(params[:quiz_id])      session[:mcq_params].deep_merge!(params[:mcq]) if params[:mcq]      @mcq = Mcq.new(session[:mcq_params])        @option_count = session[:mcq_params]['option_count']      @option_count.times { @mcq.options.build }        @mcq.quiz_id = params[:quiz_id]      @mcq.current_step = session[:mcq_step]        if params[:previous_button]        @mcq.previous_step      elsif @mcq.last_step?        @mcq.save if @mcq.valid?      else        @mcq.next_step      end      session[:mcq_step] = @mcq.current_step        if @mcq.new_record?        render "new"      else        session[:mcq_step] = session[:mcq_params] = nil        redirect_to edit_quiz_path(@mcq.quiz_id)      end    end  end  

But each time the second page is shown, the no of fields for options doubles or in case of invalid entry only the field for question_text is shown. How do I show the options correctly? Should I just go with my first solution? I'm new to rails and don't know much about the best practices.

Rails 5 Message Chat tutorial

Posted: 16 Oct 2016 07:00 AM PDT

I'm going through the rails 5 tutorial to build a message chat. I was doing so well until I came across the below error when I am trying to view is using localhost 3000.

>**uninitialized constant HomeController**     >Routes match in priority from top to bottom    >Helper HTTP Verb   Path    Controller#Action  >Path / Url       >Path Match  >/cable   >#>, @pubsub=nil, @worker_pool=nil, @event_loop=nil, >@remote_connections=nil, @connections=[]>    >new_user_session_path  GET /users/sign_in(.:format)      devise/sessions#new    >user_session_path  POST    /users/sign_in(.:format)      devise/sessions#create    >destroy_user_session_path  DELETE  /users/sign_out(.:format)     >devise/sessions#destroy    >user_password_path POST    /users/password(.:format)     >devise/passwords#create    >new_user_password_path GET /users/password/new(.:format)     >devise/passwords#new    >edit_user_password_path    GET /users/password/edit(.:format)    >devise/passwords#edit    >PATCH  /users/password(.:format)     >devise/passwords#update    >PUT    /users/password(.:format)     >devise/passwords#update    >cancel_user_registration_path  GET /users/cancel(.:format)   >devise/registrations#cancel    >user_registration_path POST    /users(.:format)      >devise/registrations#create    >new_user_registration_path GET /users/sign_up(.:format)      >devise/registrations#new    >edit_user_registration_path    GET /users/edit(.:format)     >devise/registrations#edit    >PATCH  /users(.:format)      >devise/registrations#update    >PUT    /users(.:format)      >devise/registrations#update    >DELETE /users(.:format)      >devise/registrations#destroy    >root_path  GET /     >home#index    >chat_rooms_path    GET /chat_rooms(.:format)     >chat_rooms#index    >POST   /chat_rooms(.:format)     >chat_rooms#create    >new_chat_room_path GET /chat_rooms/new(.:format)     >chat_rooms#new    >chat_room_path GET /chat_rooms/:id(.:format)     >chat_rooms#show    >GET    /     >chat_rooms#index  

I have gone through it step by step but it's still not showing anything? Any advice would be ace. I'm new to rails so bere with me :)

Basically I just want to view it on the server :( so any help would be superb.

Hartl's Tutorial Ch13 - unable to deploy to Heroku after configuring carrierwave

Posted: 16 Oct 2016 06:54 AM PDT

Ch 13.4.4 from Hartl's tutorial on "Image upload in production".

When trying to deploy to heroku, I get the following error:

Counting objects: 63, done.  Delta compression using up to 4 threads.  Compressing objects: 100% (60/60), done.  Writing objects: 100% (63/63), 12.81 KiB | 0 bytes/s, done.  Total 63 (delta 27), reused 0 (delta 0)  remote: Compressing source files... done.  remote: Building source:  remote:   remote: -----> Ruby app detected  remote: -----> Compiling Ruby/Rails  remote: -----> Using Ruby version: ruby-2.2.4  remote: -----> Installing dependencies using bundler 1.11.2  remote:        Running: bundle install --without development:test --path vendor/bundle --binstubs vendor/bundle/bin -j4 --deployment  remote:        Warning: the running version of Bundler is older than the version that created the lockfile. We suggest you upgrade to the latest version of Bundler by running `gem install bundler`.  remote:        Fetching gem metadata from https://rubygems.org/..........  remote:        Fetching version metadata from https://rubygems.org/...  remote:        Fetching dependency metadata from https://rubygems.org/..  remote:        Using rake 11.3.0  remote:        Using concurrent-ruby 1.0.2  remote:        Using i18n 0.7.0  remote:        Using minitest 5.9.1  remote:        Using thread_safe 0.3.5  remote:        Using builder 3.2.2  remote:        Using erubis 2.7.0  remote:        Using mini_portile2 2.1.0  remote:        Using rack 2.0.1  remote:        Using nio4r 1.2.1  remote:        Using websocket-extensions 0.1.2  remote:        Using mime-types-data 3.2016.0521  remote:        Using arel 7.1.3  remote:        Using execjs 2.7.0  remote:        Installing CFPropertyList 2.3.3  remote:        Using bcrypt 3.1.11  remote:        Using sass 3.4.22  remote:        Using will_paginate 3.1.0  remote:        Using coffee-script-source 1.10.0  remote:        Using method_source 0.8.2  remote:        Using thor 0.19.1  remote:        Installing excon 0.53.0  remote:        Installing json 2.0.2 with native extensions  remote:        Installing mimemagic 0.3.2  remote:        Installing formatador 0.2.5  remote:        Using multi_json 1.12.1  remote:        Installing xml-simple 1.1.5  remote:        Installing ipaddress 0.8.3  remote:        Installing trollop 2.1.2  remote:        Installing inflecto 0.0.2  remote:        Using pg 0.18.4  remote:        Installing mini_magick 4.5.1  remote:        Using puma 3.4.0  remote:        Using bundler 1.11.2  remote:        Using tilt 2.0.5  remote:        Using turbolinks-source 5.0.0  remote:        Using faker 1.6.6  remote:        Using tzinfo 1.2.2  remote:        Using nokogiri 1.6.8.1  remote:        Using rack-test 0.6.3  remote:        Using sprockets 3.7.0  remote:        Using websocket-driver 0.6.4  remote:        Using mime-types 3.1  remote:        Using autoprefixer-rails 6.5.0.2  remote:        Using uglifier 3.0.0  remote:        Using bootstrap-will_paginate 0.0.10  remote:        Using coffee-script 2.4.1  remote:        Installing fog-core 1.43.0  remote:        Installing fission 0.5.0  remote:        Using turbolinks 5.0.1  remote:        Using activesupport 5.0.0.1  remote:        Using loofah 2.0.3  remote:        Using mail 2.6.4  remote:        Using bootstrap-sass 3.3.6  remote:        Installing rbvmomi 1.8.2  remote:        Installing fog-json 1.0.2  remote:        Installing fog-xml 0.1.2  remote:        Using rails-dom-testing 2.0.1  remote:        Using globalid 0.3.7  remote:        Using activemodel 5.0.0.1  remote:        Using jbuilder 2.4.1  remote:        Using rails-html-sanitizer 1.0.3  remote:        Installing fog-local 0.3.0  remote:        Installing fog-vmfusion 0.1.0  remote:        Installing fog-brightbox 0.11.0  remote:        Installing fog-openstack 0.1.15  remote:        Installing fog-aliyun 0.1.0  remote:        Installing fog-profitbricks 2.0.1  remote:        Installing fog-sakuracloud 1.7.5  remote:        Installing fog-serverlove 0.1.2  remote:        Installing fog-softlayer 1.1.4  remote:        Installing fog-storm_on_demand 0.1.1  remote:        Installing fog-atmos 0.1.0  remote:        Installing fog-cloudatcost 0.1.2  remote:        Installing fog-aws 0.12.0  remote:        Installing fog-dynect 0.0.3  remote:        Installing fog-ecloud 0.3.0  remote:        Installing fog-google 0.1.0  remote:        Installing fog-powerdns 0.1.1  remote:        Installing fog-radosgw 0.0.5  remote:        Installing fog-rackspace 0.1.1  remote:        Installing fog-riakcs 0.1.0  remote:        Installing fog-voxel 0.1.0  remote:        Installing fog-terremark 0.1.0  remote:        Installing fog-vsphere 1.2.1  remote:        Installing fog-xenserver 0.2.3  remote:        Using activejob 5.0.0.1  remote:        Using activerecord 5.0.0.1  remote:        Using actionview 5.0.0.1  remote:        Using actionpack 5.0.0.1  remote:        Using actioncable 5.0.0.1  remote:        Using actionmailer 5.0.0.1  remote:        Using railties 5.0.0.1  remote:        Using sprockets-rails 3.2.0  remote:        Using coffee-rails 4.2.1  remote:        Using jquery-rails 4.1.1  remote:        Using rails 5.0.0.1  remote:        Using sass-rails 5.0.6  remote:        Installing carrierwave 0.11.2  remote:        Installing fog 1.38.0  remote:        Bundle complete! 28 Gemfile dependencies, 100 gems now installed  remote:        Gems in the groups development and test were not installed.  remote:        Bundled gems are installed into ./vendor/bundle.  remote:        Bundle completed (8.97s)  remote:        Cleaning up the bundler cache.  remote:        Warning: the running version of Bundler is older than the version that created the lockfile. We suggest you upgrade to the latest version of Bundler by running `gem install bundler`.  remote: -----> Preparing app for Rails asset pipeline  remote:        Running: rake assets:precompile  remote:        rake aborted!  remote:        ArgumentError: Missing required arguments: aws_access_key_id, aws_secret_access_key  remote:        /tmp/build_d6e56f1586e33307e3549a279f377845/vendor/bundle/ruby/2.2.0/gems/fog-core-1.43.0/lib/fog/core/service.rb:244:in `validate_options'  remote:        /tmp/build_d6e56f1586e33307e3549a279f377845/vendor/bundle/ruby/2.2.0/gems/fog-core-1.43.0/lib/fog/core/service.rb:268:in `handle_settings'  remote:        /tmp/build_d6e56f1586e33307e3549a279f377845/vendor/bundle/ruby/2.2.0/gems/fog-core-1.43.0/lib/fog/core/service.rb:98:in `new'  remote:        /tmp/build_d6e56f1586e33307e3549a279f377845/vendor/bundle/ruby/2.2.0/gems/fog-core-1.43.0/lib/fog/core/services_mixin.rb:16:in `new'  remote:        /tmp/build_d6e56f1586e33307e3549a279f377845/vendor/bundle/ruby/2.2.0/gems/fog-core-1.43.0/lib/fog/storage.rb:27:in `new'  remote:        /tmp/build_d6e56f1586e33307e3549a279f377845/vendor/bundle/ruby/2.2.0/gems/carrierwave-0.11.2/lib/carrierwave/uploader/configuration.rb:83:in `eager_load_fog'  remote:        /tmp/build_d6e56f1586e33307e3549a279f377845/vendor/bundle/ruby/2.2.0/gems/carrierwave-0.11.2/lib/carrierwave/uploader/configuration.rb:96:in `fog_credentials='  remote:        /tmp/build_d6e56f1586e33307e3549a279f377845/config/initializers/carrier_wave.rb:3:in `block in <top (required)>'  remote:        /tmp/build_d6e56f1586e33307e3549a279f377845/vendor/bundle/ruby/2.2.0/gems/carrierwave-0.11.2/lib/carrierwave/uploader/configuration.rb:118:in `configure'  remote:        /tmp/build_d6e56f1586e33307e3549a279f377845/vendor/bundle/ruby/2.2.0/gems/carrierwave-0.11.2/lib/carrierwave.rb:14:in `configure'  remote:        /tmp/build_d6e56f1586e33307e3549a279f377845/config/initializers/carrier_wave.rb:2:in `<top (required)>'  remote:        /tmp/build_d6e56f1586e33307e3549a279f377845/vendor/bundle/ruby/2.2.0/gems/activesupport-5.0.0.1/lib/active_support/dependencies.rb:287:in `load'  remote:        /tmp/build_d6e56f1586e33307e3549a279f377845/vendor/bundle/ruby/2.2.0/gems/activesupport-5.0.0.1/lib/active_support/dependencies.rb:287:in `block in load'  remote:        /tmp/build_d6e56f1586e33307e3549a279f377845/vendor/bundle/ruby/2.2.0/gems/activesupport-5.0.0.1/lib/active_support/dependencies.rb:259:in `load_dependency'  remote:        /tmp/build_d6e56f1586e33307e3549a279f377845/vendor/bundle/ruby/2.2.0/gems/activesupport-5.0.0.1/lib/active_support/dependencies.rb:287:in `load'  remote:        /tmp/build_d6e56f1586e33307e3549a279f377845/vendor/bundle/ruby/2.2.0/gems/railties-5.0.0.1/lib/rails/engine.rb:648:in `block in load_config_initializer'  remote:        /tmp/build_d6e56f1586e33307e3549a279f377845/vendor/bundle/ruby/2.2.0/gems/activesupport-5.0.0.1/lib/active_support/notifications.rb:166:in `instrument'  remote:        /tmp/build_d6e56f1586e33307e3549a279f377845/vendor/bundle/ruby/2.2.0/gems/railties-5.0.0.1/lib/rails/engine.rb:647:in `load_config_initializer'  remote:        /tmp/build_d6e56f1586e33307e3549a279f377845/vendor/bundle/ruby/2.2.0/gems/railties-5.0.0.1/lib/rails/engine.rb:612:in `block (2 levels) in <class:Engine>'  remote:        /tmp/build_d6e56f1586e33307e3549a279f377845/vendor/bundle/ruby/2.2.0/gems/railties-5.0.0.1/lib/rails/engine.rb:611:in `each'  remote:        /tmp/build_d6e56f1586e33307e3549a279f377845/vendor/bundle/ruby/2.2.0/gems/railties-5.0.0.1/lib/rails/engine.rb:611:in `block in <class:Engine>'  remote:        /tmp/build_d6e56f1586e33307e3549a279f377845/vendor/bundle/ruby/2.2.0/gems/railties-5.0.0.1/lib/rails/initializable.rb:30:in `instance_exec'  remote:        /tmp/build_d6e56f1586e33307e3549a279f377845/vendor/bundle/ruby/2.2.0/gems/railties-5.0.0.1/lib/rails/initializable.rb:30:in `run'  remote:        /tmp/build_d6e56f1586e33307e3549a279f377845/vendor/bundle/ruby/2.2.0/gems/railties-5.0.0.1/lib/rails/initializable.rb:55:in `block in run_initializers'  remote:        /tmp/build_d6e56f1586e33307e3549a279f377845/vendor/bundle/ruby/2.2.0/gems/railties-5.0.0.1/lib/rails/initializable.rb:44:in `each'  remote:        /tmp/build_d6e56f1586e33307e3549a279f377845/vendor/bundle/ruby/2.2.0/gems/railties-5.0.0.1/lib/rails/initializable.rb:44:in `tsort_each_child'  remote:        /tmp/build_d6e56f1586e33307e3549a279f377845/vendor/bundle/ruby/2.2.0/gems/railties-5.0.0.1/lib/rails/initializable.rb:54:in `run_initializers'  remote:        /tmp/build_d6e56f1586e33307e3549a279f377845/vendor/bundle/ruby/2.2.0/gems/railties-5.0.0.1/lib/rails/application.rb:352:in `initialize!'  remote:        /tmp/build_d6e56f1586e33307e3549a279f377845/config/environment.rb:5:in `<top (required)>'  remote:        /tmp/build_d6e56f1586e33307e3549a279f377845/vendor/bundle/ruby/2.2.0/gems/railties-5.0.0.1/lib/rails/application.rb:328:in `require'  remote:        /tmp/build_d6e56f1586e33307e3549a279f377845/vendor/bundle/ruby/2.2.0/gems/railties-5.0.0.1/lib/rails/application.rb:328:in `require_environment!  remote:        /tmp/build_d6e56f1586e33307e3549a279f377845/vendor/bundle/ruby/2.2.0/gems/railties-5.0.0.1/lib/rails/application.rb:448:in `block in run_tasks_blocks'  remote:        /tmp/build_d6e56f1586e33307e3549a279f377845/vendor/bundle/ruby/2.2.0/gems/sprockets-rails-3.2.0/lib/sprockets/rails/task.rb:62:in `block (2 levels) in define'  remote:        /tmp/build_d6e56f1586e33307e3549a279f377845/vendor/bundle/ruby/2.2.0/gems/rake-11.3.0/exe/rake:27:in `<top (required)>'  remote:        Tasks: TOP => environment  remote:        (See full trace by running task with --trace)  remote:  !  remote:  !     Precompiling assets failed.  remote:  !  remote:  !     Push rejected, failed to compile Ruby app.  remote:   remote:  !     Push failed  remote: Verifying deploy...  remote:   remote: !   Push rejected to octopus-sample-app.  remote:   To https://git.heroku.com/octopus-sample-app.git   ! [remote rejected] master -> master (pre-receive hook declined)  error: failed to push some refs to 'https://git.heroku.com/octopus-sample-app.git'  

My carrer_wave.rb looks like this:

if Rails.env.production?    CarrierWave.configure do |config|      config.fog_credentials = {        :provider              => 'AWS',        :aws_access_key_id     => ENV['S3_ACCESS_KEY'],        :aws_secret_access_key => ENV['S3_SECRET_KEY'],        :region                => ENV['S3_REGION']      }      config.fog_directory     = ENV['S3_BUCKET']    end  end  

And I'm sure I've configured the AWS access key, secret key, region and bucket properly, which I've confirmed by looking under config vars in the Heroku app.

How to debug errors in Rails, Capistrano, Puma deployment

Posted: 16 Oct 2016 06:26 AM PDT

Ok, I have an app that I deploy with Capistrano. In order to set it I've roughly followed the instructions here and all was working ok.

After my last deployment, it stopped working. I haven't changed anything significant other a Model and Controller (no change in the config itself that I can remember). Here's what I'm getting in Puma's error log:

    ArgumentError: wrong number of arguments (0 for 1)      /var/www/apps/MyAPP/shared/bundle/ruby/2.2.0/gems/actionview-4.2.1/lib/action_view/helpers/debug_helper.rb:25:in `debug'      /var/www/apps/MyAPP/shared/bundle/ruby/2.2.0/gems/sprockets-rails-2.3.3/lib/sprockets/railtie.rb:133:in `block (2 levels) in <class:Railtie>'      /var/www/apps/MyAPP/shared/bundle/ruby/2.2.0/gems/activesupport-4.2.1/lib/active_support/lazy_load_hooks.rb:38:in `instance_eval'      /var/www/apps/MyAPP/shared/bundle/ruby/2.2.0/gems/activesupport-4.2.1/lib/active_support/lazy_load_hooks.rb:38:in `execute_hook'      /var/www/apps/MyAPP/shared/bundle/ruby/2.2.0/gems/activesupport-4.2.1/lib/active_support/lazy_load_hooks.rb:28:in `block in on_load'      /var/www/apps/MyAPP/shared/bundle/ruby/2.2.0/gems/activesupport-4.2.1/lib/active_support/lazy_load_hooks.rb:27:in `each'      /var/www/apps/MyAPP/shared/bundle/ruby/2.2.0/gems/activesupport-4.2.1/lib/active_support/lazy_load_hooks.rb:27:in `on_load'      /var/www/apps/MyAPP/shared/bundle/ruby/2.2.0/gems/sprockets-rails-2.3.3/lib/sprockets/railtie.rb:129:in `block in <class:Railtie>'      /var/www/apps/MyAPP/shared/bundle/ruby/2.2.0/gems/activesupport-4.2.1/lib/active_support/lazy_load_hooks.rb:36:in `call'      /var/www/apps/MyAPP/shared/bundle/ruby/2.2.0/gems/activesupport-4.2.1/lib/active_support/lazy_load_hooks.rb:36:in `execute_hook'      /var/www/apps/MyAPP/shared/bundle/ruby/2.2.0/gems/activesupport-4.2.1/lib/active_support/lazy_load_hooks.rb:45:in `block in run_load_hooks'      /var/www/apps/MyAPP/shared/bundle/ruby/2.2.0/gems/activesupport-4.2.1/lib/active_support/lazy_load_hooks.rb:44:in `each'      /var/www/apps/MyAPP/shared/bundle/ruby/2.2.0/gems/activesupport-4.2.1/lib/active_support/lazy_load_hooks.rb:44:in `run_load_hooks'      /var/www/apps/MyAPP/shared/bundle/ruby/2.2.0/gems/railties-4.2.1/lib/rails/application/finisher.rb:62:in `block in <module:Finisher>'      /var/www/apps/MyAPP/shared/bundle/ruby/2.2.0/gems/railties-4.2.1/lib/rails/initializable.rb:30:in `instance_exec'      /var/www/apps/MyAPP/shared/bundle/ruby/2.2.0/gems/railties-4.2.1/lib/rails/initializable.rb:30:in `run'      /var/www/apps/MyAPP/shared/bundle/ruby/2.2.0/gems/railties-4.2.1/lib/rails/initializable.rb:55:in `block in run_initializers'      /usr/local/rvm/rubies/ruby-2.2.2/lib/ruby/2.2.0/tsort.rb:226:in `block in tsort_each'      /usr/local/rvm/rubies/ruby-2.2.2/lib/ruby/2.2.0/tsort.rb:348:in `block (2 levels) in each_strongly_connected_component'      /usr/local/rvm/rubies/ruby-2.2.2/lib/ruby/2.2.0/tsort.rb:429:in `each_strongly_connected_component_from'      /usr/local/rvm/rubies/ruby-2.2.2/lib/ruby/2.2.0/tsort.rb:347:in `block in each_strongly_connected_component'      /usr/local/rvm/rubies/ruby-2.2.2/lib/ruby/2.2.0/tsort.rb:345:in `each'      /usr/local/rvm/rubies/ruby-2.2.2/lib/ruby/2.2.0/tsort.rb:345:in `call'      /usr/local/rvm/rubies/ruby-2.2.2/lib/ruby/2.2.0/tsort.rb:345:in `each_strongly_connected_component'      /usr/local/rvm/rubies/ruby-2.2.2/lib/ruby/2.2.0/tsort.rb:224:in `tsort_each'      /usr/local/rvm/rubies/ruby-2.2.2/lib/ruby/2.2.0/tsort.rb:203:in `tsort_each'      /var/www/apps/MyAPP/shared/bundle/ruby/2.2.0/gems/railties-4.2.1/lib/rails/initializable.rb:54:in `run_initializers'      /var/www/apps/MyAPP/shared/bundle/ruby/2.2.0/gems/railties-4.2.1/lib/rails/application.rb:352:in `initialize!'      /var/www/apps/MyAPP/current/config/environment.rb:5:in `<top (required)>'      /var/www/apps/MyAPP/current/config.ru:3:in `require'      /var/www/apps/MyAPP/current/config.ru:3:in `block in <main>'      /var/www/apps/MyAPP/shared/bundle/ruby/2.2.0/gems/rack-1.6.4/lib/rack/builder.rb:55:in `instance_eval'      /var/www/apps/MyAPP/shared/bundle/ruby/2.2.0/gems/rack-1.6.4/lib/rack/builder.rb:55:in `initialize'      /var/www/apps/MyAPP/current/config.ru:in `new'      /var/www/apps/MyAPP/current/config.ru:in `<main>'      /var/www/apps/MyAPP/shared/bundle/ruby/2.2.0/gems/rack-1.6.4/lib/rack/builder.rb:49:in `eval'      /var/www/apps/MyAPP/shared/bundle/ruby/2.2.0/gems/rack-1.6.4/lib/rack/builder.rb:49:in `new_from_string'      /var/www/apps/MyAPP/shared/bundle/ruby/2.2.0/gems/rack-1.6.4/lib/rack/builder.rb:40:in `parse_file'      /var/www/apps/MyAPP/shared/bundle/ruby/2.2.0/gems/puma-2.14.0/lib/puma/configuration.rb:143:in `load_rackup'      /var/www/apps/MyAPP/shared/bundle/ruby/2.2.0/gems/puma-2.14.0/lib/puma/configuration.rb:96:in `app'      /var/www/apps/MyAPP/shared/bundle/ruby/2.2.0/gems/puma-2.14.0/lib/puma/runner.rb:113:in `load_and_bind'      /var/www/apps/MyAPP/shared/bundle/ruby/2.2.0/gems/puma-2.14.0/lib/puma/single.rb:79:in `run'      /var/www/apps/MyAPP/shared/bundle/ruby/2.2.0/gems/puma-2.14.0/lib/puma/cli.rb:215:in `run'      /var/www/apps/MyAPP/shared/bundle/ruby/2.2.0/gems/puma-2.14.0/bin/puma:10:in `<top (required)>'      /var/www/apps/MyAPP/shared/bundle/ruby/2.2.0/bin/puma:23:in `load'      /var/www/apps/MyAPP/shared/bundle/ruby/2.2.0/bin/puma:23:in `<top (required)>'  

Looking at the error, I can't really see what's going... any ideas?

Error when pushing up to Heroku

Posted: 16 Oct 2016 06:16 AM PDT

As I am new to RoR, Heroku and Ubuntu, this error is failing me! What can I do?

Ben

See Picture

error during installing ruby on rails application uninitialized constant Gem::BasicSpecification (NameError)

Posted: 16 Oct 2016 06:16 AM PDT

I am trying to install ruby on rails application fedena on Ubuntu server.

It uses some old ruby library. I followed the instructions on

http://paritosh.passion8.co.in/post/49878771105/fedena-installation-guide

 gem install rubygems-update -v=1.3.7  /usr/lib/ruby/vendor_ruby/rubygems/defaults/operating_system.rb:43:in `<top (required)>': uninitialized constant Gem::BasicSpecification (NameError)          from /usr/local/lib/site_ruby/2.3.0/rubygems.rb:1113:in `require'          from /usr/local/lib/site_ruby/2.3.0/rubygems.rb:1113:in `<top (required)>'          from <internal:gem_prelude>:4:in `require'          from <internal:gem_prelude>:4:in `<internal:gem_prelude>'  

Unknown key: :order in Mailboxer Gem

Posted: 16 Oct 2016 06:44 AM PDT

I am currently trying to use the Mailboxer Gem. I have added the following line in my Gemfile:

gem "mailboxer"  

In the konsole I did these:

$ bundle install  $ rails g mailboxer:install  $ rake db:migrate  $ rails g mailboxer:views  

and have added acts_as_messageable in my user.rb. However, I am getting this error

enter image description here

I tried replacing the gem in Gemfile from gem 'mailboxer'' to gem 'mailboxer', github: 'mailboxer/mailboxer' but I get this message when I bundle install

git://github.com/mailboxer/mailboxer.git (at master@0e41d6a) is not yet checked out. Run `bundle install` first.  

How can I fix this and make the mailboxer work in my rails application?

Apache2 suburl with Rails app and WebPage

Posted: 16 Oct 2016 05:35 AM PDT

ServerName ######.net ServerAdmin ##@###.net

    PassengerRuby /home/###/.rbenv/versions/2.2.4/bin/ruby      Documentroot /home/##/##/MainWebApp/public      <Directory /home/##/##/MainWebApp/public>           AllowOverride all           Options -MultiViews           Require all granted      </Directory>        Alias /mail/ "/var/www/html"        <Directory "/var/www/html">           Options -MultiViews           AllowOverride all           Order allow,deny           Allow from all      </Directory>          ErrorLog ${APACHE_LOG_DIR}/error.log      CustomLog ${APACHE_LOG_DIR}/access.log combined  

example.net loads the page from ruby on rails. But example.net/mail does not load the index.php page @ location "/var/www/html". It gives a rails routing error

Bootstrap Navbar on RoR overflows from the navbar when it is an active class

Posted: 16 Oct 2016 05:26 AM PDT

I am building a website using Ruby on Rails however there is a bug that I cannot fix. Whenever there is an active menu in my navbar, everything overflows from the navbar. My active class takes up the entire space of the container.

I am not sure what I'm doing wrong because I am still following tutorials.

Whichever from the navbar menu is active it does this behavior.

This is my navbar.scss

// Contains all navbar-related CSS  @import "bootstrap-sprockets";  @import "bootstrap";  @import "colors.scss";    .navbar{    margin: 0px;    height: 60px;    padding-top: 10px;    border: 0px;    background-color: $dark-blue!important;    }    .navbar-logo{    float: left;    font-size: 18px;    line-height: 20px;    height: 50px;    padding: 0px;  }    #iptulogo {    float: right;    margin-right: 10px;    margin-left: 5px;    font-size: 1.5em;    color: $gray;    text-transform: uppercase;    letter-spacing: -1px;    padding-top: 9px;    font-weight: bold;    &:hover {      color: white;      text-decoration: none;    }  }    .navbar-default .navbar-nav li>a,  .navbar-default .navbar-nav li > a.dropdown-toggle{    color: $gray!important;    background-color: $dark-blue!important;    padding-bottom: 14px;    //display: inline;    &:hover, &:focus{      color: $gray;      background-color: lighten($dark-blue,10%) !important;    }  }    .navbar-default .navbar-nav .active a,  .navbar-default .navbar-nav .active a.dropdown-toggle{    color: $gray;    background: none;    border-bottom: 5px solid $gray;    padding-bottom: 10px;    max-width: 100%;    //display: inline;    &:hover, &:focus{      color: $gray;      background: lighten($dark-blue,10%);    }   }  button.navbar-toggle.collapsed,  ul.dropdown-menu{    background-color: $dark-blue;    &:hover, &:focus{      background-color: $dark-blue;    }   }    This is my navbar.html.slim
header.navbar.navbar-default.navbar-fixed-top role="navigation" "navigation"    .container      .navbar-header        button.navbar-toggle.collapsed type="button" data-toggle="collapse" data-target=".navbar-collapse" aria-expanded="false" aria-controls="false"          span.sr-only Toggle Navigation          span.icon-bar          span.icon-bar          span.icon-bar        .navbar-logo          = link_to image_tag("logo/UPD_logo.png", style:"max-height: 40px;"), root_path, id:"logo"          = link_to "UP IPTTU", root_path, id: "iptulogo"      .navbar-collapse.collapse                        ul.nav.navbar-nav          li            = active_link_to "Home", home_path, :wrap_tag => :li          li            = active_link_to "About Us", about_path, :wrap_tag => :li          li            = active_link_to "Expertise", expertise_path, :wrap_tag => :li          li.dropdown            a.dropdown-toggle data-toggle="dropdown" href="#"              | Opportunities            ul.dropdown-menu role="menu"              li                = link_to "IP Offers", ip_offers_path              li                = link_to "IP Needs", ip_needs_path          li            = active_link_to "ITSO-IPOPHL", itso_ipophl_path, :wrap_tag => :li          li            = active_link_to "Resources", resources_path, :wrap_tag => :li        - if logged_in?          ul.nav.navbar-nav.navbar-right            li.dropdown              a.dropdown-toggle data-toggle="dropdown" href="#"                | Account                span.caret              ul.dropdown-menu role="menu"                li                  = link_to "Profile", current_user                li                  = link_to "Settings", edit_user_path(current_user)                li.divider                li                  = link_to "Logout", logout_path, method: "delete"        - else          ul.nav.navbar-nav.navbar-right            li              = active_link_to "Log in", login_path, :wrap_tag => :li            li              = active_link_to "Register", register_path, :wrap_tag => :li

Using Heroku w/o depending on add-ons

Posted: 16 Oct 2016 05:25 AM PDT

I've got a startup that's bootstrapped & they're currently deciding between AWS, DO, & Heroku. There's no dev-ops, so Heroku is a clear winner there, but the pricing of memcached + redis + elasticsearch begins to get heavy.

I'd like to use Heroku as an app server and AWS EC2 to house elasticsearch, redis, and memcached...is this a bad idea? Would it make more sense to keep everything under AWS?

If we can stick with Heroku for our app server, what's the most inexpensive way to connect our services? (Redis, memcached, elasticsearch)

What dangers do we run if we don't have a dev-ops and just do digital ocean (capistrano + rails)?

how to pass string value in `find_by_sql`

Posted: 16 Oct 2016 05:03 AM PDT

Using query like:

Campaign.find_by_sql("select c.*,sc.*,org.name as org_name from campaigns as c left join super_campaigns as sc ON sc.id= c.super_campaign_id left join organisations as org ON org.id= c.organisation_id where c.status=0 AND sc.status='active'")

Getting error after using sc.status='active'.Thanks.

Chaining associated objects won't allow me to call their attributes Rails

Posted: 16 Oct 2016 04:21 AM PDT

I'm in need of some help. I have been making a blog site in Rails to work on some gems and other techniques and I ran into a problem. I am calling a comment partial into my blog show page as shown here:

show.html.slim:

- if notice != nil  p#notice.alert.alert-success role='alert' = notice    h1 Blog Post    h4 Title: #{@blog_post.title}    h4 Author: #{@blog_post.user.name}    h4 Entry:  p = @blog_post.blog_entry    = render partial: 'comments/form', locals: { comment: @comment }    .panel.panel-default    .panel-heading      h4 Comments    #js-comments.panel-body      = render partial: 'comments/comment', collection: @blog_post.comments    = link_to 'Feed', blog_posts_path, class: 'btn btn-primary'  

The issue is in the comments/comment partial:

.panel-body    p      strong        = comment.user.username      |  said at       span.posted-at        = comment.created_at.strftime('%m/%d/%Y %H:%M:%S')      | :     p = comment.comment_entry    - if policy(comment).update?      = link_to 'Edit Comment', edit_blog_post_comment_path(comment.blog_post, comment), class: 'btn btn-primary'    - if policy(comment).destroy?      = link_to 'Destroy Comment', [comment.blog_post, comment], method: :delete, data: { confirm: 'Are you sure?' }, class: 'btn btn-primary'  

Now when I call comment.user.username or comment.created_at.strftime, I got NoMethodError messages saying that username and strftime are undefined methods. However, if I call comment.user and comment.created_at, it works just fine. For some reason it just won't let me add that additional attribute to the chain. I can verify that all the correct associations are in place between the user, blog_post, and comments.

Just in case, here is my blog controller for the show page:

def show    @comment = @blog_post.comments.new  end  

Any help would be greatly appreciated. Thanks!

RabbitMq: Message lost from queue when exceptions occurred during message processing

Posted: 16 Oct 2016 07:10 AM PDT

I am ruby on rails developer. i am using rabbitMQ in my project to processed some data as soon as the data comes in queue. i am using bunny gem a rabbitMQ client that provide interface to interact with RabbitMq.

My issue is that whenever an exceptions occurred or server stops unexpectedly while processing data from queue my message from the queue is lost.

I want to know how people deal with lost messages from the rabbitMQ queue. is there any way to get those messages back for processing.

how to update records in RSpec model spec?

Posted: 16 Oct 2016 04:12 AM PDT


I'm trying to find out some good solution for updating records while Rails model testing using RSpec, but I didn't found any exact solution on the internet. So, I'm posting this question with dummy problem and the solution(in answers). I hope that it'll help many other programmers.

So, let's move towards the dummy problem :

Let say I've three rails model which are item, inventory & purchase.

  • item : allow me to create a new Item with the presence of item_name.
  • inventory : allow me to view and update available quantity of an item, with the presence of item_id & item_quantity.
    The inventory will be automatically created just after the creation of the item with current item's id and with zero quantity.
  • purchase : allow me to update the item's inventory, with the presence of item_id & item_quantity.
    When we create a new purchase it'll automatically update the item_quantity in inventory table.

Here is the code inside the model's file

Item.rb

has_one :inventory  validates_presence_of :name  after_create :create_inventory    private    def create_inventory      Inventory.create(item_id:self.id, quantity: 0)    end  


Inventory.rb

belongs_to :item  validates_presence_of :quantity, :item_id  


Purchase.rb

validates_presence_of :item_id, :quantity  after_create :update_inventory  private      def update_inventory          @item = Item.find(self.item_id)          @inventory = @item.inventory          @inventory.update_column('quantity', @inventory.quantity+self.quantity)      end  



So, here is the Question :
I've an item with quantity of 100 and I want to update it's quantity in the inventory before purchasing more quantity for the same.
So, if I have to write the model spec for the purchase model then, how can I update item's inventory value to 100 after creating the item in the model spec ? Because there is no FactoryGirl method to update the records.


Experienced programmers are welcome to improve this question.

Rails: Why doesn't devise sign_up show username in registrations/view [duplicate]

Posted: 16 Oct 2016 03:49 AM PDT

This question already has an answer here:

I want to a username field to be shown in my devise: user view. However, when I added the field in view, it doesn't show (even when I use developer tools on chrome).

Below is my current code for users/registrations/new.html.erb:

<h2>Sign up</h2>    <%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>    <%= devise_error_messages! %>      <div class="field">      <%= f.label :username %><br />      <%= f.text_field :username, autofocus: true %>    </div>          <div class="field">      <%= f.label :email %><br />      <%= f.email_field :email %>    </div>      <div class="field">      <%= f.label :password %>      <% if @minimum_password_length %>      <em>(<%= @minimum_password_length %> characters minimum)</em>      <% end %><br />      <%= f.password_field :password, autocomplete: "off" %>    </div>      <div class="field">      <%= f.label :password_confirmation %><br />      <%= f.password_field :password_confirmation, autocomplete: "off" %>    </div>      <div class="actions">      <%= f.submit "Sign up" %>    </div>  <% end %>    <%= render "users/shared/links" %>  

I would appreciate any guidance on this problem.

Rails postgres sql view missing data when creating via migration

Posted: 16 Oct 2016 03:42 AM PDT

I've been speeding up some statistics reports in my rails(4.2.7, postgres 9.5 database) project via creating sql views.

I wrote all code in PGAdmin, checked all data in views. Than I generated migration in my rails project and copied all written sql code to migration.

When I run migration, all views are being created with randomly missing data.

Example:

create or replace view revenue_by_date as    select sum(reward) as reward_coins, count(ot.id) as amount, (sum(reward)::float / substring(value from '---\s''(\d+)''')::bigint) as reward_dollars,    ot.created_at::date as date    from offerwall_transactions ot    inner join settings on var = 'exchange_rate'    where ot.reward > 1    group by ot.created_at::date, settings.value;  

I get reward_dollars data missing. Query result

However, when creating via PGA data is ok Normal Query result

I have same problems with other views. Some views are created with no data at all.

Where is a mistake?

Ignore uppercase, downcase and accent in search

Posted: 16 Oct 2016 03:24 AM PDT

I have a search system with filter here. This system work like a charm but I have some problem with downcase / uppercase and accent.

For example if I search "marée" I have result but if I search "MAREE" or "Marée" or "maree". I don't have result.

I want to fix that. How I can fix this ? Thank you.

my controller

    def resultnohome            if params[:query].blank?              redirect_to action: :index and return            else            @campings = Camping.searchi(params[:query], params[:handicap], params[:animaux], params[:television], params[:plage], params[:etang], params[:lac])              if params[:query] == "aube"                @pub = Camping.find_by_id(1)              else              end          end  end  

My model

 def self.searchi(query, handicap, animaux, television, plage, etang, lac)      return scoped unless query.present?           result = left_outer_joins(:caracteristiquetests, :situations).where('nomdep LIKE ? OR name LIKE ? OR nomregion LIKE ? OR commune LIKE?', "%#{query}%", "%#{query}%", "%#{query}%", "%#{query}%")           result = result.where('handicap LIKE ?', "%#{handicap}%") if handicap           result = result.where('animaux LIKE ?', "%#{animaux}%") if animaux           result = result.where('television LIKE ?', "%#{television}%") if television           result = result.where('plage LIKE ?', "%#{plage}%") if plage           result = result.where('etang LIKE ?', "%#{etang}%") if etang           result = result.where('lac LIKE ?', "%#{lac}%") if lac        return result    end  

Git commit and then pull in branch, from master. Loosing everything?

Posted: 16 Oct 2016 07:38 AM PDT

I am working on a completely different structure from the one on master branch, on a On Rails app in a local branch. I am comiting everything and then pushing my changes to a remote branch as well. At some point in future, I would like to integrate my changes back into master, but I want to make it even first, so I won't be behind it, just ahead by n commits. If I am doing a

git pull origin master  

into my branch and then push that, would I loose anything from my previous commits, or would those stay on top of the master branch ones? In theory I should be able to merge my branch, as I will only be ahead of master, but I am not entirely sure if that's how git is working

Ruby Twitter gem followers method repeating 20 times rather than displaying first 20 followers

Posted: 16 Oct 2016 03:23 AM PDT

so im using the ruby twitter gem and api in conjunction with omniauth, to log into twitter via a simple rails app, and return the first 20 followers of a user. The main piece of code to do this is a method in a lib file stating:

def followers      client.followers.take(20)  end  

For some reason, the app works perfectly locally, but after being deployed to heroku, it displays my first follower, 20 times repeated, as opposed to the first 20 followers. Any help would be appreciated. Here is my code:

I have a basic twitter api app in rails, which works perfectally locally, however when I pushed to Heroku it doesn't work and upon checking the logs there is an error saying uninitialized constant WelcomeController::TwitterApi. I can not find out how to rectify this. Many thanks.

lib/twitter_api.rb

class TwitterApi    def initialize(user)      @user = user    end      def our_public_tweets      client.user_timeline(user, count: 1, exclude_replies: true, include_rts: false)    end      def followers      client.followers.take(20)    end      private      attr_reader :user      def client      @client ||= Twitter::REST::Client.new do |config|        config.consumer_key = Rails.application.secrets.twitter_api_key        config.consumer_secret = Rails.application.secrets.twitter_api_secret        config.access_token = user.token        config.access_token_secret = user.secret      end    end  end  

application_controller.rb

class ApplicationController < ActionController::Base    protect_from_forgery with: :exception      def current_user      @current_user ||= User.find(session[:user_id]) if session[:user_id]    end      # to enable the current_user variable to be used in the view file    helper_method :current_user    end  

welcome_controller.rb

class WelcomeController < ApplicationController    require 'twitter_api'      def index      @twitter_api = TwitterApi.new(current_user)    end  end  

views/welcome/index.html.erb

<div class="wrapper">    <h1>OMNIAUTH AND TWITTER API</h1>      <!-- <%= link_to "Sign in with Twitter", "/auth/twitter" %> -->    <% if current_user %>      <div id="sign_in_wrapper">        <p id="sign_in">Signed in as <span><%= current_user.name %></span> </p>        <%= image_tag current_user.profile_image, class: "profile_image" %>        <p><%= link_to "Sign out", signout_path, id: "sign_out" %></p>      </div>        <div class="public_tweets">        <p>Latest tweet from <%= current_user.name %>:</p>        <% @twitter_api.our_public_tweets.each do |tweet| %>          <% cache('our_public_tweets', expires_in: 6.hours) do %>            <%= parsed_tweet(tweet) %>          <% end %>        <% end %>      </div>        <ul class="followers">        <p>First 20 followers for <%= current_user.name %>:</p>        <% @twitter_api.followers.each do |follower| %>          <% cache('followers', expires_in: 6.hours) do %>            <li><%= follower.name %></li>            <hr>          <% end %>        <% end %>      </ul>      <% else %>        <%= link_to "/auth/twitter", id: "link_button" do %>        <i class="fa fa-twitter fa-3x"></i>      <% end %>      <p class="date">Click the twitter icon to sign in and view followers</p>      <% end %>  </div>  

models/user.rb

class User < ApplicationRecord    def self.from_omniauth(auth_hash)      #Look up the user or create them using keys in the auth hash      user = where(provider: auth_hash.provider, uid: auth_hash.uid).first_or_create      user.update(        name: auth_hash.info.name,        profile_image: auth_hash.info.image,        twitter_user_name: auth_hash.info.nickname,        token: auth_hash.credentials.token,        secret: auth_hash.credentials.secret      )      user    end      # token and secret is what came back from omniauth and this was saved to the user database.  end  

application_helper.rb

module ApplicationHelper      def parsed_tweet(tweet)      _parsed_tweet = tweet.text.dup        tweet.urls.each do |entity|        html_link = link_to(entity.display_url.to_s, entity.expanded_url.to_s, target: 'blank')        _parsed_tweet.sub!(entity.url.to_s, html_link)      end        tweet.media.each do |entity|        html_link = link_to(entity.display_url.to_s, entity.expanded_url.to_s, target: 'blank')        _parsed_tweet.sub!(entity.url.to_s, html_link)      end        _parsed_tweet.html_safe    end  end  

Most Searched for Keyword, in Elastic Search

Posted: 16 Oct 2016 05:13 AM PDT

In Elastic Search, how do I get the strings that are searched for the most number of times? I tried getting this result, but was not successful.

For eg: Multiple users searches for work 'stackoverflow'. What is the total number of times, ElasticSearch has searched for the work 'stackoverflow'

or as an aggregation:

stackoverflow: 98 times
redcarpet: 40 times

... ...

How to capture HTML5 microphone input to icecast?

Posted: 16 Oct 2016 05:02 AM PDT

What are the steps and means of capturing microphone audio stream through HTML5 / Javascript (no flash) and then sending it to an already set up icecast server?

The solution must be solely browser/web-based, no additional software. The server is on Rails 5.0.0.1.

Where should I start?

I'm struggling to find any relevant info online as everything talks about uploading/recording audio files as complete files, not streams.

Ruby on Rails : Find record of an object withour querying database

Posted: 16 Oct 2016 06:46 AM PDT

i want to know how to get a specific record from an object example

@user = User.all  

but in index.html.erb , i want to show only the record that in the 3th order , i try :

<% @user.each do |u| %>  

but this give me all the records.

i found this :

<% @user.find{|b| b.id == 1}%>    <%= @service.full_name%>  

but didn't work and i don't know how to use it right in index.html.erb.

Request spec with devise_token_auth + omniauth

Posted: 16 Oct 2016 01:59 AM PDT

I'm currently writing an API with Rails 5 using devise_token_auth and omniauth as authentication strategy.

To check if the omniauth authentication works, I wrote a request spec:

OmniAuth.config.test_mode = true  OmniAuth.config.mock_auth[:facebook] = OmniAuth::AuthHash.new(    {        provider: 'facebook',        uid: '123456'    })  Rails.application.env_config["devise.mapping"] = Devise.mappings[:user]  Rails.application.env_config["omniauth.auth"]  = OmniAuth.config.mock_auth[:facebook]  get '/omniauth/facebook/callback'  expect(response).to have_http_status(:ok)  

When I run the test I have to following error:

NoMethodError: undefined method `[]' for nil:NilClass  /Users/gaetan/.rvm/gems/ruby-2.3.1/gems/devise_token_auth-0.1.39/app/controllers/devise_token_auth/omniauth_callbacks_controller.rb:14:in `redirect_callbacks'  

Here is the line 14:

devise_mapping = [request.env['omniauth.params']['namespace_name'],  

So I guess that's because omniauth.params is nil. Does it mean that I also have to mock the params? How?

Rails model to pull data from REST api and save to database

Posted: 16 Oct 2016 01:33 AM PDT

I'm making an app that needs to make an API request every 15 mins, put that data into a database, and put then load the data into highcharts objects.

How do I generate a model that will have these values that will have corresponding table columns: id, calls_offered, calls_handled, timestamp

Additionally how do I access that data to dynamically update the charts I have created?

Bonus question: will that automatically pass over to Heroku when I deploy to it?

Rails - expecting <"categories/index"> but rendering with <[]>

Posted: 16 Oct 2016 01:36 AM PDT

I am trying to run a test but see the below error

"CreateCategoriesTest#test_get_new_category_form_and_create_category [/Users/imcglobal/Desktop/RailsDevelopement/blog/test/integration/create_categories_test.rb:10]: expecting <"categories/index"> but rendering with <[]>"

below are the test details

test "get new category form and create category" do      get new_category_path      assert_template 'categories/new'      assert_difference 'Category.count', 1 do          post categories_path, category: {name: "sports"}      end      assert_template 'categories/index' **#line 10**      assert_match "sports", response.body  end      #categories controller  def index      @categories = Category.all  end  

My index file loops through categories object. Can anyone please let me know what i am missing. Thanks.

Preventing adding duplicates to Cart

Posted: 16 Oct 2016 01:21 AM PDT

So here's the action that i'm testing out in my controller

def add_to_cart      @cart = current_cart      if @cart.tutors.where(params[:tutor_id]).empty?        @cart.add_tutor(params[:tutor_id])        flash[:success] = 'You have successfully added the tutor to your shortlist!'        redirect_to show_path      else        flash[:danger] = 'You have already shortlisted the tutor!'        redirect_to show_path      end    end  

I'm not sure if this is the correct way to go about testing if tutor_id is present in the cart. I actually tried testing various methods of checking for the children's properties in rails console. I arrived at Parent.Child.where(:id => X) as a way to check if any of the children has id = X.

This is what shows up in my server (or development log) when the method is called.

Started POST "/add_to_cart/11" for 116.87.14.150 at 2016-10-16 07:32:09 +0000  Cannot render console from 116.87.14.150! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255  Processing by CartsController#add_to_cart as HTML    Parameters: {"authenticity_token"=>"XzHaIJMzIz9I84W5tmLuj+28SBvVP9pc1JdZOyQaYEr286JNIw4J8tKtSON7eIWsdf0Lc6ogCdT2LrdtVVxGoA==", "tutor_id"=>"11"}  cart_id = 17    Cart Load (0.2ms)  SELECT  "carts".* FROM "carts" WHERE "carts"."id" = ? LIMIT 1  [["id", 17]]     (0.2ms)  SELECT COUNT(*) FROM "tutors" INNER JOIN "cart_tutors" ON "tutors"."id" = "cart_tutors"."tutor_id" WHERE "cart_tutors"."cart_id" = ? AND (11)  [["cart_id", 17]]  

Anyway it constantly processes the else portion which means its not working like i meant it to be, which probably means that its not checking for the ID like i intend for it to do. Am i using the correct method? If not, how should i be doing it insteaD?

Rails ActiveRecord find a table attribute's value given conditions in 2 tables

Posted: 16 Oct 2016 04:54 AM PDT

I have 2 tables:

  1. A conversations table that contains a list of conversations with their IDs (and two users ids associated to each ('recipient_id' and 'sender_id').
  2. A messages table that contains messages associated to one of the existing conversations. Every instance of Message includes a boolean attribute 'read' (defaults false) intended to show if there are any unread messages in a conversation.

So Conversation has_many :messages and Message belongs_to :conversation

My objective is to check if the current_user has any unread messages (in any of his existing conversations) to display a general alert. So far I've managed to display an alert for each conversation but I'm struggling to find an efficient way to implement a general one.

My original approach was to:

  1. Find the last message in each of the current user's conversations.
  2. Evaluate if each of those last messages were sent by the current user AND if read == false.
  3. Return true if any of those last messages met these condition.

This translated into the following code:

  @conversations = current_user.conversations    @unread = []    if @conversations.exists?          @conversations.each do |conversation|          if conversation.messages.exists?            if conversation.messages.last.user_id != current_user.id && conversation.messages.last.read == false              @unread << true            end          end        end    end      @unread.include?(true)  end  

I'm quite new coding but it seems a pretty inefficient method having to loop through all current_users conversations and creating an array to check if there's any 'true' value on it.

I'd loop through the messages themselves but an instance only has the user_id of the sender so if I don't link it with the Conversation model there's no way to know if a message was sent to him.

Could you help with an efficient way to achieve this with a more appropriate Active Record query or a better approach.

By the way, not sure if matters but I'm using postgresql in my dev environment.

Thanks

How to combine and sort arrays with jbuilder

Posted: 16 Oct 2016 12:38 AM PDT

I want to create two arrays that render different partials, then combine and sort them on an attribute, and add that array to a key in the response.

  a = json.array!([1,2,3]) do |company|      json.value(company.to_s) # This is a different partial to below    end      b = json.array!([1,2,4]) do |person|      json.value(person.to_s) # Different partial from above    end      ## Do something here  

Result should be

{     stuff: [{:value=>"1"},             {:value=>"1"},             {:value=>"2"},             {:value=>"2"},             {:value=>"3"},             {:value=>"4"}]   }  

I tried this, but it does sort it

json.stuff do    (json.array!([1,2,3]) do |company|      json.value(company.to_s)    end + json.array!([1,2,4]) do |person|      json.value(person.to_s)    end).sort_by{|y| y[:value]}      # (people_json + people_json)  end  

Rails: Nginx + Capistrano all good but not work

Posted: 16 Oct 2016 12:06 AM PDT

I am deploying an app using Nginx and Capstrano,
sudo service nginx restart everything is ok
cap production deploy also all passed

But can not visit the website and error is

ERR_CONNECTION_REFUSED

Strange thing is before cap production deploy , website shows

Welcome to Nginx

After cap production deploy and db migration is done, nothing shows on the website and error happens.

How to debug this in situation. What causes this problem and how to fix this?

Thanks

No comments:

Post a Comment