Tuesday, March 15, 2016

Rails: DRYing up before_action | Fixed issues

Rails: DRYing up before_action | Fixed issues


Rails: DRYing up before_action

Posted: 15 Mar 2016 06:53 AM PDT

I have a few controllers:

class First < ApplicationController     before_action: do_this     before_action: do_this_too  end    class Second < ApplicationController    before_action: do_this    before_action: do_this_too  end    class Third < ApplicationController    end  

Two of the controllers have the same before_action's method. How do I dry up this code so that the First and Second class use the before_action in one location but not the Third class?

I am thinking of some kind of class inheritance solution. Any ideas? In my real world example I have more classes with multiple identical before_actions on each?

private_pub with Puma on heroku

Posted: 15 Mar 2016 06:42 AM PDT

I'm trying to deploy my production app on Heroku. I'm using both private_pub and Puma in my app.

I wanted to start both using this procfile :

web: bundle exec puma -C config/puma.rb  web: bundle exec rackup private_pub.ru -s thin -p $PORT -E production  

But it fails, it seems like you can have only one web process running at a time on Heroku apps. Is there a way to initialize both ?

Line Chart is showing current Date counts on its previous date using Chartkick

Posted: 15 Mar 2016 06:30 AM PDT

Line Chart is showing current Date counts on its previous day using Chartkick with highcharts. In the below mentioned HASH, It clearly shows 49 count on August 23, 2015. But when it renders the chart. it shows 49 on August 22, 2015. am i missing something? Any idea, how i can fix it ?

 @timeline_chart ={["Team", "August 21, 2015"]=>0, ["Team", "August 22,   2015"]=>1, ["Team", "August 23, 2015"]=>7, ["Company", "August 21, 2015"]=>1, ["Company", "August 22, 2015"]=>4, ["Company", "August 23, 2015"]=>49}  

Query:

 @timeline_chart =     Model.group(:impressionable_type).group_by_day(:created_at, format: "%B %d, %Y").count  

call:

line_chart @timeline_chart  

How to create controller spec to test unauthorized access, redirect and message

Posted: 15 Mar 2016 06:27 AM PDT

I am trying to create controller specs, in this case for a user who is not authorized to access this resource. I need to detect the status, location of redirect, and message from Devise/ Cancan.

After much hacking away, I came up with this.

context 'with unauthorized user' do    describe 'GET #index' do      subject { xhr :get, :index, {} }      it { subject; response.status.should eq 401 } #successfully detects unauthorized      it { should redirect_to new_user_session_path } #Expected response to be a <redirect>, but was <401>      it 'redirects' do         get :index, {}        expect(response).to redirect_to(new_user_session_path) #successfully detects redirect        # how to get the Devise message?      end    end  end  

Could someone please help me to understand what is happening here.

  1. What is the difference between xhr :get, :index and get :index, {}.
  2. What is the difference between subject; response.status.should eq 401 and `response.status.should eq 401'
  3. How to I get the message from the response?

Trouble with the rake db:migrate command

Posted: 15 Mar 2016 06:17 AM PDT

rake db:migrate  

Stack trace

> == 20160315111403 Books: migrating ============================================  > -- create_table(:books) rake aborted! An error has occurred, all later migrations canceled:    Error:    > Mysql2::Error: Table 'books' already exists: CREATE TABLE `books`  > (`id` int(11) auto_increment PRIMARY KEY, `title` varchar(32) NOT  > NULL, `price` float, `subject_id` int(11), `description` text,  > `created_at` datetime)  > ENGINE=InnoDB/home/paritosh/.rvm/gems/ruby-2.2.3/gems/activerecord-4.2.4/lib/active_record/connection_adapters/abstract_mysql_adapter.rb:305:in  > `query'  > /home/paritosh/.rvm/gems/ruby-2.2.3/gems/activerecord-4.2.4/lib/active_record/connection_adapters/abstract_mysql_adapter.rb:305:in  > `block in execute'  > /home/paritosh/.rvm/gems/ruby-2.2.3/gems/activerecord-4.2.4/lib/active_record/connection_adapters/abstract_adapter.rb:473:in `block in log'  > /home/paritosh/.rvm/gems/ruby-2.2.3/gems/activesupport-4.2.4/lib/active_support/notifications/instrumenter.rb:20:in  > `instrument'  > /home/paritosh/.rvm/gems/ruby-2.2.3/gems/activerecord-4.2.4/lib/active_record/connection_adapters/abstract_adapter.rb:467:in `log'  > /home/paritosh/.rvm/gems/ruby-2.2.3/gems/activerecord-4.2.4/lib/active_record/connection_adapters/abstract_mysql_adapter.rb:305:in  > `execute'  > /home/paritosh/.rvm/gems/ruby-2.2.3/gems/activerecord-4.2.4/lib/active_record/connection_adapters/mysql2_adapter.rb:231:in  > `execute'  > /home/paritosh/.rvm/gems/ruby-2.2.3/gems/activerecord-4.2.4/lib/active_record/connection_adapters/abstract/schema_statements.rb:208:in  > `create_table'  > /home/paritosh/.rvm/gems/ruby-2.2.3/gems/activerecord-4.2.4/lib/active_record/connection_adapters/abstract_mysql_adapter.rb:468:in  > `create_table'  > /home/paritosh/.rvm/gems/ruby-2.2.3/gems/activerecord-4.2.4/lib/active_record/migration.rb:662:in  > `block in method_missing'  > /home/paritosh/.rvm/gems/ruby-2.2.3/gems/activerecord-4.2.4/lib/active_record/migration.rb:631:in  > `block in say_with_time'  > /home/paritosh/.rvm/gems/ruby-2.2.3/gems/activerecord-4.2.4/lib/active_record/migration.rb:631:in  > `say_with_time'  > /home/paritosh/.rvm/gems/ruby-2.2.3/gems/activerecord-4.2.4/lib/active_record/migration.rb:651:in  > `method_missing'  > /home/paritosh/.rvm/gems/ruby-2.2.3/gems/activerecord-4.2.4/lib/active_record/migration.rb:416:in  > `method_missing'  > /home/paritosh/library/db/migrate/20160315111403_books.rb:4:in `up'  > /home/paritosh/.rvm/gems/ruby-2.2.3/gems/activerecord-4.2.4/lib/active_record/migration.rb:568:in  > `up'  > /home/paritosh/.rvm/gems/ruby-2.2.3/gems/activerecord-4.2.4/lib/active_record/migration.rb:608:in  > `exec_migration'  > /home/paritosh/.rvm/gems/ruby-2.2.3/gems/activerecord-4.2.4/lib/active_record/migration.rb:589:in  > `block (2 levels) in migrate'  > /home/paritosh/.rvm/gems/ruby-2.2.3/gems/activerecord-4.2.4/lib/active_record/migration.rb:588:in  > `block in migrate'  > /home/paritosh/.rvm/gems/ruby-2.2.3/gems/activerecord-4.2.4/lib/active_record/connection_adapters/abstract/connection_pool.rb:292:in  > `with_connection'  > /home/paritosh/.rvm/gems/ruby-2.2.3/gems/activerecord-4.2.4/lib/active_record/migration.rb:587:in  > `migrate'  > /home/paritosh/.rvm/gems/ruby-2.2.3/gems/activerecord-4.2.4/lib/active_record/migration.rb:765:in  > `migrate'  > /home/paritosh/.rvm/gems/ruby-2.2.3/gems/activerecord-4.2.4/lib/active_record/migration.rb:995:in  > `block in execute_migration_in_transaction'  > /home/paritosh/.rvm/gems/ruby-2.2.3/gems/activerecord-4.2.4/lib/active_record/migration.rb:1043:in  > `ddl_transaction'  > /home/paritosh/.rvm/gems/ruby-2.2.3/gems/activerecord-4.2.4/lib/active_record/migration.rb:994:in  > `execute_migration_in_transaction'  > /home/paritosh/.rvm/gems/ruby-2.2.3/gems/activerecord-4.2.4/lib/active_record/migration.rb:956:in  > `block in migrate'  > /home/paritosh/.rvm/gems/ruby-2.2.3/gems/activerecord-4.2.4/lib/active_record/migration.rb:952:in  > `each'  > /home/paritosh/.rvm/gems/ruby-2.2.3/gems/activerecord-4.2.4/lib/active_record/migration.rb:952:in  > `migrate'  > /home/paritosh/.rvm/gems/ruby-2.2.3/gems/activerecord-4.2.4/lib/active_record/migration.rb:820:in  > `up'  > /home/paritosh/.rvm/gems/ruby-2.2.3/gems/activerecord-4.2.4/lib/active_record/migration.rb:798:in  > `migrate'  > /home/paritosh/.rvm/gems/ruby-2.2.3/gems/activerecord-4.2.4/lib/active_record/tasks/database_tasks.rb:137:in  > `migrate'  > /home/paritosh/.rvm/gems/ruby-2.2.3/gems/activerecord-4.2.4/lib/active_record/railties/databases.rake:44:in  > `block (2 levels) in <top (required)>'  > /home/paritosh/.rvm/gems/ruby-2.2.3/gems/rake-10.0.4/lib/rake/task.rb:246:in  > `call'  > /home/paritosh/.rvm/gems/ruby-2.2.3/gems/rake-10.0.4/lib/rake/task.rb:246:in  > `block in execute'  > /home/paritosh/.rvm/gems/ruby-2.2.3/gems/rake-10.0.4/lib/rake/task.rb:241:in  > `each'  > /home/paritosh/.rvm/gems/ruby-2.2.3/gems/rake-10.0.4/lib/rake/task.rb:241:in  > `execute'  > /home/paritosh/.rvm/gems/ruby-2.2.3/gems/rake-10.0.4/lib/rake/task.rb:184:in  > `block in invoke_with_call_chain'  > /home/paritosh/.rvm/gems/ruby-2.2.3/gems/rake-10.0.4/lib/rake/task.rb:177:in  > `invoke_with_call_chain'  > /home/paritosh/.rvm/gems/ruby-2.2.3/gems/rake-10.0.4/lib/rake/task.rb:170:in  > `invoke'  > /home/paritosh/.rvm/gems/ruby-2.2.3/gems/rake-10.0.4/lib/rake/application.rb:143:in  > `invoke_task'  > /home/paritosh/.rvm/gems/ruby-2.2.3/gems/rake-10.0.4/lib/rake/application.rb:101:in  > `block (2 levels) in top_level'  > /home/paritosh/.rvm/gems/ruby-2.2.3/gems/rake-10.0.4/lib/rake/application.rb:101:in  > `each'  > /home/paritosh/.rvm/gems/ruby-2.2.3/gems/rake-10.0.4/lib/rake/application.rb:101:in  > `block in top_level'  > /home/paritosh/.rvm/gems/ruby-2.2.3/gems/rake-10.0.4/lib/rake/application.rb:110:in  > `run_with_threads'  > /home/paritosh/.rvm/gems/ruby-2.2.3/gems/rake-10.0.4/lib/rake/application.rb:95:in  > `top_level'  > /home/paritosh/.rvm/gems/ruby-2.2.3/gems/rake-10.0.4/lib/rake/application.rb:73:in  > `block in run'  > /home/paritosh/.rvm/gems/ruby-2.2.3/gems/rake-10.0.4/lib/rake/application.rb:160:in  > `standard_exception_handling'  > /home/paritosh/.rvm/gems/ruby-2.2.3/gems/rake-10.0.4/lib/rake/application.rb:70:in  > `run'  > /home/paritosh/.rvm/gems/ruby-2.2.3/bin/ruby_executable_hooks:15:in  > `eval'  > /home/paritosh/.rvm/gems/ruby-2.2.3/bin/ruby_executable_hooks:15:in  > `<main>' Tasks: TOP => db:migrate (See full trace by running task with  > --trace)  

How to replace following active record query with association?

Posted: 15 Mar 2016 06:20 AM PDT

I have developed rails sample app.Here i have made a scope named_scope :from_users_followed_by, lambda { |user| followed_by(user) }

def self.followed_by(user)    followed_ids = %(SELECT followed_id FROM relationships WHERE follower_id = :user_id) { :conditions => ["user_id IN (#{followed_ids}) OR user_id = :user_id", { :user_id => user }] }  end  

This scope is responsible for feed of microposts in user home page. Now I have been asked to write this scope with Association.So please help me .

Add values to Ruby JSON Object

Posted: 15 Mar 2016 06:27 AM PDT

I am working on Ruby on Rails. I have JSON object like this in my database:

{"data":[      {"name":"A", "available":"1"},      {"name":"B", "available":"0"}  ]}  

I want to update this by adding another record and it should look like:

{"data":[          {"name":"A", "available":"1"},          {"name":"B", "available":"0"},          {"name":"C","available":"1"}      ]}  

How can I do this?

Why assert_select is not accepting parameters rails 4.2?

Posted: 15 Mar 2016 06:05 AM PDT

I am working on rails integration tests, someone wrote tests that were passing at that time but now they are giving warning

here is the line of code i was working on

assert_select "a[href=/monster_xml_users/#{user_xml.id}][data-method=delete]", I18n.t('revoke_access')  

But now it is giving warning

Invalid CSS selector, Assertion not run

But if i write it alternatively like this

 assert_select "a", I18n.t('revoke_access')          assert_select "a" do            assert_select "[href=?]","/monster_xml_users/#{user_xml.id}"            assert_select "[data-method=?]", "delete"          end  

Then it gives no warning and tests pass and it is correct. But i am unable to figure out why previous assertion is failing now ? Has assert_select syntax is changed now in Rails 4.2 ?

Storing logs in separate database using secondbase and audited gem

Posted: 15 Mar 2016 06:29 AM PDT

I'm having a Rails 4 application with database PostgreSQL. I want to store all log changes of topic model in a different database. Is it possible to use secondbase and audited gem together. What is the best way to do it?. I have been trying this for a week with secondbase and audited by modifying the gem. Internally in audited gem i added secondbase and inherited audit module from SecondBase::Base instead of ActiveRecord::Base

How to pass currently signed in user id to resolve block in ui-router state? (AngularJS)

Posted: 15 Mar 2016 05:50 AM PDT

I'm trying to pass the currently signed-in user to the resolve block of a 'user' state (I'm using ui-router), so upon sign-in, user will be in url of .../users/:id.

Other routes are nested inside :user route, so this seems the most logical path to me (I may be wrong).

I'm using angular_devise here so i should be able to extract the :id from from API via Auth, but I'm running into some trouble.

(Included other possible relevant files below.)

App.js

$stateProvder    .state('users', {         url: '/users/{id}',         templateUrl: 'home/_home.html',        controller: 'MainCtrl',        resolve: {            userPromise: ['$stateParams', 'users', 'Auth', function($stateParams, users, Auth) {              return users.get(                  Auth.currentUser().then(function (user) {                  return user.id;              })            );        }]      }    })  

Users.js

.factory('users', ['$http', function($http) {      var u = {          userArray: []      };      u.get = function(id) {          return $http.get('/users/' + id + '.json').then(function(res) {              console.log('request: ', res.data);              angular.copy(res.data, u.userArray);            });      };      return u;  }]);  

Users_controller.rb

class UsersController < ApplicationController      def show          @user = User.find(params[:id])          authorize @user          respond_with @user      end  end  

NavCtrl.js

.controller('NavCtrl', [      '$scope',      'Auth',      function($scope, Auth) {          $scope.signedIn = Auth.isAuthenticated;          $scope.logout = Auth.logout;            Auth.currentUser().then(function (user) {              $scope.user = user;          });            $scope.$on('devise:new-registration', function (e, user) {              $scope.user = user;          });            $scope.$on('devise:login', function (e, user) {              $scope.user = user;          });            $scope.$on('devise:logout', function (e, user) {              $scope.user = {};          });      }])  ;  

FYI. $http request is being sent to a rails backend.

I would be very grateful if anyone can advise what i might be doing wrong.

Template errors when running on heroku, but not locally

Posted: 15 Mar 2016 06:32 AM PDT

My rails app is working perfectly when I run it locally, then when I push it to heroku i get the following error:

ActionView::Template::Error (undefined method `[]' for nil:NilClass)  

And the error relates to the following code:

<!DOCTYPE html>  <html lang="en">    <%= render 'layouts/head' %>    <body>    <div class="brand"> <%= image_tag('gaisce.png', class: 'img-responsive', alt: 'Logo')%></div>  <div class="address-bar"></div>    <!-- Navigation -->  <nav class="navbar navbar-default" role="navigation">      <div class="container">          <!-- Brand and toggle get grouped for better mobile display -->          <div class="navbar-header">              <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">                  <span class="sr-only">Toggle navigation</span>                  <span class="icon-bar"></span>                  <span class="icon-bar"></span>                  <span class="icon-bar"></span>              </button>              <!-- navbar-brand is hidden on larger screens, but visible when the menu is collapsed -->              <a class="navbar-brand" href="index.html">My App</a>          </div>          <!-- Collect the nav links, forms, and other content for toggling -->          <div class ="stretch">              <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">                  <ul class="nav navbar-nav">                      <li>                          <a href="index.html">Home</a>                      </li>                      <li>                          <a href="about.html">Personal</a>                      </li>                      <li>                          <a href="blog.html">Physical</a>                      </li>                      <li>                          <a href="contact.html">Community</a>                      </li>                      <li>                          <a href="contact.html">Progress Tracker</a>                      </li>                  </ul>              </div>          </div>          <!-- /.navbar-collapse -->      </div>      <!-- /.container -->  </nav>    <div class="container">        <div class="row">          <div class="box">              <div class="col-lg-12 text-center">                  <div id="carousel-example-generic" class="carousel slide">                      <!-- Indicators -->                      <ol class="carousel-indicators hidden-xs">                          <li data-target="#carousel-example-generic" data-slide-to="0" class="active"></li>                          <li data-target="#carousel-example-generic" data-slide-to="1"></li>                          <li data-target="#carousel-example-generic" data-slide-to="2"></li>                      </ol>                        <!-- Wrapper for slides -->                      <div class="carousel-inner">                          <div class="item active">                              <%= image_tag('adven.jpg', class: 'img-responsive img-full',alt:'')%>                          </div>                          <div class="item">                              <%= image_tag('sport.jpg', class: 'img-responsive img-full',alt:'')%>                          </div>                          <div class="item">                              <%= image_tag('adventure.jpg', class: 'img-responsive img-full',alt:'')%>                          </div>                      </div>                        <!-- Controls -->                      <a class="left carousel-control" href="#carousel-example-generic" data-slide="prev">                          <span class="icon-prev"></span>                      </a>                      <a class="right carousel-control" href="#carousel-example-generic" data-slide="next">                          <span class="icon-next"></span>                      </a>                  </div>                  <h2 class="brand-before">                      <small>Welcome to</small>                  </h2>                  <h1 class="brand-name">My App</h1>                  <hr class="tagline-divider">                  <h2 class="brand-before">                      <small>You can log your weekly activities while completely your Award, and keep track of your progress!</small>                  </h2>                  </div>          </div>      </div>        <div class="row">          <div class="box">              <div class="col-lg-12">                  <hr>                  <h1 class="intro-text text-center">Personal Activity                  </h2>                  <hr>                  <hr class="visible-xs">                </div>          </div>      </div>        <div class="row">          <div class="box">              <div class="col-lg-12">                  <hr>                  <h1 class="intro-text text-center">Physical Activity                  </h2>                  <hr>                  <hr class="visible-xs">                </div>          </div>      </div>                <div class="row">          <div class="box">              <div class="col-lg-12">                  <hr>                  <h1 class="intro-text text-center">Community Activity                  </h2>                  <hr>                  <hr class="visible-xs">                </div>          </div>      </div>                <div class="row">          <div class="box">              <div class="col-lg-12">                  <hr>                  <h1 class="intro-text text-center">Progress Tracker                  </h2>                  <hr>                  <hr class="visible-xs">                </div>          </div>      </div>    </div>  <!-- /.container -->      <%= render 'layouts/footer' %>    <!-- jQuery -->  <script src="javascripts/jquery.js"></script>    <!-- Bootstrap Core JavaScript -->  <script src="javascripts/bootstrap.min.js"></script>    <!-- Script to Activate the Carousel -->  <script>  $('.carousel').carousel({      interval: 5000 //changes the speed  })  </script>  

Can anybody tell me why this code would work when running locally, but not on heroku?

Proper way to execute raw SQL with Postgres

Posted: 15 Mar 2016 05:26 AM PDT

At the moment when I need to execute a complex query that can't be expressed with Arel I do something like this:

q = "-- complex stuff here"  sql = ActiveRecord::Base.send(:sanitize_sql_array, [q, x, y, z])  ActiveRecord::Base.connection.execute(sql)  

I don't like calling private method to sanitize user input, is there a better way?

Form not updating Database with Select Tag Ruby

Posted: 15 Mar 2016 05:51 AM PDT

I have recently added a new column to my table in the database called "sport". I am trying to update the value in the column using a select_tag in a form however everytime I have tried the data has not updated. The rest of the form is currently working and updating correctly.

The select tag is currently implemented like this inside my view.

<%= f.label :sport %>  <%= select_tag(:sport, options_for_select([['Basketball', 1], ['NRL', 2], ['Super Rugby', 3], ['AFL', 4], ['eSports', 5], ['Ice Hockey', 6], ['Horse Racing', 7], ['Tennis', 8], ['NFL', 9] ]))%>  

:sport is declared as an integer within the table.

The controller currently looks like this:

class BetsController < ApplicationController      def new      @bet = Bet.new    end      def create      @bets = Bet.new(bet_params)        if @bets.save          flash[:success] = 'Bet Successfull Logged.'          redirect_to new_bet_path        else          flash[:danger] = 'Error, Bet has not been logged. Try again mate.'          redirect_to new_bet_path        end    end      def show      @bet = Bet.find(params[:id])    end      def edit      @bet = Bet.find(params[:id])    end      def update      @bet = Bet.find(params[:id])            if @bet.update_attributes(bet_params)              flash[:success] = "Bet Updated!"              redirect_to bet_path(params[:id])          else              render action: :edit          end    end      private        def bet_params        params.require(:bet).permit(:bet_placed, :game, :units_placed, :odds, :profit_or_loss, :date_of_bet, :resolved, :push, :sport, :bookmaker)      end    end  

How do I properly call methods in views?

Posted: 15 Mar 2016 06:00 AM PDT

I installed https://github.com/ryanto/acts_as_votable gem. I tried various stuff authors showed in documentation via Rails console. However I do not understand how to call these methods in views.

def vote      @post.liked_by current_user  end  

This for example is my view. Delete and edit work well, however Vote does not. What is a proper way to do this?

<% if current_user?(post.user) %>      <%= link_to "delete", post, method: :delete %>,      <%= link_to "edit", edit_post_path(post)%>    <% end %>    <%= link_to "vote", post, method: :vote if logged_in? %>  

Rails logger level changes to ERROR abruptly

Posted: 15 Mar 2016 04:53 AM PDT

I am experiencing very strange behavior with my Rails logs. Wherein the logger level automatically/abruptly changes to ERROR(:error. logger level code 3) instead of whatever it was supposed to be (:debug or :info).

Here in this image the log level is as expected. Debug or level 0

good logs showing all info. level 0 means debug

But within few minutes(at most 2 minutes) the logger level changes to 3(3 stands for ERROR)

enter image description here

I came across a github issue which explains Rails logger is not thread safe, I am using passenger in thread mode as opposed to process which it was previously. Could this be a reason for such behavior ?

What could be other possibilities, that changes the logger level from 0 to 3 ?

Custom Headers in Nginx

Posted: 15 Mar 2016 04:51 AM PDT

i have this nginx.conf

server {    listen  <%= ENV['NGINX_IP'] %>:<%= ENV['NGINX_PORT'] %>;  server_name proxy-oapp.rhcloud.com;      location / {      proxy_set_header X-Real-IP $remote_addr;      #proxy_set_header Host $http_host;      proxy_set_header X-forwarded-for $proxy_add_x_forwarded_for;      proxy_set_header X-NginX-Proxy true;      proxy_pass https://app-oapp.rhcloud.com;      proxy_redirect off;    }    location /api {      proxy_set_header Host api-oapp.rhcloud.com;      proxy_set_header X-forwarded-for $proxy_add_x_forwarded_for;      proxy_set_header X-NginX-Proxy true;      proxy_set_header X_Auth_Token $upstream_http_x_auth_token;      proxy_set_header X_User_Id $upstream_http_x_user_id;      proxy_pass https://api-oapp.rhcloud.com/;       proxy_redirect off;    }  }  

The client add in headers the id and the token for authentication as: X_Auth_Token: MYTOKEN X_User_Id: MYID

But in the server i haven't the token in the headers.

WHY????

Uninitialized constant Rails when i tried to run Rails.cache.clear in capistrano task when deployed to vps?

Posted: 15 Mar 2016 04:40 AM PDT

I tried to run

Rails.cache.clear  

by Capistrano task when i deploy my app to the server. This is my code

namespace :deploy do      desc 'Clear memcache'      task :clear_memcache do        on roles(:app) , in: :sequence, wait: 2 do          Rails.cache.clear          CACHE.flush        end      end        before :starting,     :check_revision      after  :finishing,    :compile_assets      after  :finishing,    :cleanup      after  :finishing,    :copy_missing_css      after  :finishing,    :clear_cache      after  :finishing,    :clear_memcache      after  :finishing,    :restart  end  

But i got this error.

The deploy has failed with an error: #<NameError: uninitialized constant Rails>  

How can i fix this?

Thanks!

Rails admin panel loading slow

Posted: 15 Mar 2016 04:23 AM PDT

I am currently working on rails project with Mongoid ORM. I am using Rails admin gem for data handling at server side. Rails version is 4.1.7, Ruby is 2.1.5. Problem is it takes lot of time to load when admin panel is loaded the first time.

I checked the logs of rails. It appears to query each and every user from "user" table and certainly time taken to load the panel is proportional to number of entries in the user table.

Please help me in speeding the loading of panel. If any other information is required, please ask. Thanks.

Following is the snapshot of rails log.

 MOPED: 127.0.0.1:27017 QUERY        database=yeloapp_development collection=users selector={"$query"=>{"_id"=>BSON::ObjectId('5656bd857261693fb10a0000')}, "$orderby"=>{:_id=>1}} flags=[] limit=-1 skip=0 batch_size=nil fields  =nil runtime: 10.0400ms    MOPED: 127.0.0.1:27017 QUERY        database=yeloapp_development collection=users selector={"$query"=>{"_id"=>BSON::ObjectId('56ae41fe72616930bf030000')}, "$orderby"=>{:_id=>1}} flags=[] limit=-1 skip=0 batch_size=nil fields  =nil runtime: 0.4920ms    MOPED: 127.0.0.1:27017 QUERY        database=yeloapp_development collection=users selector={"$query"=>{"_id"=>BSON::ObjectId('567d01277261695b8a000000')}, "$orderby"=>{:_id=>1}} flags=[] limit=-1 skip=0 batch_size=nil fields  =nil runtime: 5.1850ms    MOPED: 127.0.0.1:27017 QUERY        database=yeloapp_development collection=users selector={"$query"=>{"_id"=>BSON::ObjectId('568cad1a7261691ff2030000')}, "$orderby"=>{:_id=>1}} flags=[] limit=-1 skip=0 batch_size=nil fields  =nil runtime: 0.5010ms    MOPED: 127.0.0.1:27017 QUERY        database=yeloapp_development collection=users selector={"$query"=>{"_id"=>BSON::ObjectId('561144df726169602d000000')}, "$orderby"=>{:_id=>1}} flags=[] limit=-1 skip=0 batch_size=nil fields  =nil runtime: 2.4130ms    MOPED: 127.0.0.1:27017 QUERY        database=yeloapp_development collection=users selector={"$query"=>{"_id"=>BSON::ObjectId('56ae487e72616930bf460000')}, "$orderby"=>{:_id=>1}} flags=[] limit=-1 skip=0 batch_size=nil fields  =nil runtime: 0.4500ms    MOPED: 127.0.0.1:27017 QUERY        database=yeloapp_development collection=users selector={"$query"=>{"_id"=>BSON::ObjectId('567d01277261695b8a000000')}, "$orderby"=>{:_id=>1}} flags=[] limit=-1 skip=0 batch_size=nil fields  =nil runtime: 5.1940ms    MOPED: 127.0.0.1:27017 QUERY        database=yeloapp_development collection=users selector={"$query"=>{"_id"=>BSON::ObjectId('56aa51f972616944d1300000')}, "$orderby"=>{:_id=>1}} flags=[] limit=-1 skip=0 batch_size=nil fields  =nil runtime: 6.2580ms  

Ability.rb

class Ability    include CanCan::Ability      def initialize(user)      # Define abilities for the passed in user here. For example:      #      #   user ||= User.new # guest user (not logged in)      #   if user.admin?      #     can :manage, :all      #   else      #     can :read, :all      #   end      #      # The first argument to `can` is the action you are giving the user      # permission to do.      # If you pass :manage it will apply to every action. Other common actions      # here are :read, :create, :update and :destroy.      #      # The second argument is the resource the user can perform the action on.      # If you pass :all it will apply to every resource. Otherwise pass a Ruby      # class of the resource.      #      # The third argument is an optional hash of conditions to further filter the      # objects.      # For example, here the user can only update published articles.      #      #   can :update, Article, :published => true      #      # See the wiki for details:      # https://github.com/CanCanCommunity/cancancan/wiki/Defining-Abilities      if user &&  user.admin_type == 1        can :access, :rails_admin       # only allow admin users to access Rails Admin        can :dashboard          can :manage, :all      end      if user && user.is_admin?         can :access, :rails_admin       # only allow admin users to access Rails Admin        can :dashboard          can :read, :all        can :manage, :statistic      end    end  end  

rails_admin.rb

RailsAdmin.config do |config|      ### Popular gems integration    ## == Devise ==    config.authenticate_with do      warden.authenticate! scope: :user    end    config.current_user_method(&:current_user)      ## == Cancan ==    #config.authorize_with :cancan      ## == PaperTrail ==    # config.audit_with :paper_trail, 'User', 'PaperTrail::Version' # PaperTrail >= 3.0.0      ### More at https://github.com/sferik/rails_admin/wiki/Base-configuration      config.actions do      dashboard                     # mandatory      index                         # mandatory      new      export      bulk_delete      show      edit      delete      show_in_app        ## With an audit adapter, you can add:      # history_index      # history_show    end  end  

rails partial passing param got empty variable

Posted: 15 Mar 2016 04:21 AM PDT

I try to pass a param to a partial in view

controller

def addMovie    @movies = Movie.all    @vid = Movie.new  end  

view

<%= render partial: "shared/videoList", videoList: :movies %>  

partial stored in app/views/sharead

<% if @videoList.present? %>      <% @videoList.each do |movie| %>  

videoList is empty ... why?

Sidekiq remote server setup

Posted: 15 Mar 2016 04:40 AM PDT

I want to run sidekiq workers remotly on different servers to split load. Could not find any documentation for it. I could not find anything in the official sidekiq documentation and I have tried in google to search for 'sidekiq remote server', 'sidekiq remote workers' ..., but could not find anything useful. Here is what I am trying to to enter image description here

My questions are: Do I need to replicate the same application code as on production server to all sidekicks servers? How to configure sidekiq to work this way or what documentation or sources to read about this type of configuration? Thanks allot to everyone for any type of help!

Image change between view templates stopping onclick dropdown menu?

Posted: 15 Mar 2016 04:49 AM PDT

I placed an onclick dropdown menu in my top navigation bar. In the top navigation bar, I wanted to change this image in my new.html.erb view template:

<li class="navigation-bar-right"> <span class="create"> <%= link_to image_tag("createpost.svg"),new_post_url, method: :get %> </span> </li>  

I copied the entire navigation bar code from application.html.erb & added it to the top of new.html.erb, changing createpost.svg to createone.svg :

<li class="navigation-bar-right"> <span class="create"> <%= link_to image_tag("createone.svg"),new_post_url, method: :get %> </span> </li>  

However, although the image changed, the onclick dropdown menu is no longer working in my new.html.erb view template..

Tried many solutions & can't figure this out. Any help would be amazing - thank you!!

application.html.erb

<% if user_signed_in? %>    <ul class="navigation-bar">     <div class="navigation-bar-right-inset">     <li class="navigation-bar-right"> <span class="create"> <%= link_to image_tag("createpost.svg"),new_post_url, method: :get %> </span> </li>      <li class="navigation-bar-right"> <span class="home"> <%= link_to image_tag("home.svg"), posts_url, data: {no_turbolink: true} %> </span> </li>      <li class="navigation-bar-right" id="drop"> <span class="settings"> <a href="#"> <img class="#" src="/assets/settings.svg"> </a> </span>        <ul class="dropdown">          <li> <%= link_to "Profile", edit_user_registration_path, method: :get %> </li>          <li> <%= link_to "Log out", destroy_user_session_url, method: :delete %> </li>           </ul>      </li>   </div>    </ul>   

new.html.erb

<% if user_signed_in? %>    <ul class="navigation-bar">     <div class="navigation-bar-right-inset">     <li class="navigation-bar-right"> <span class="create"> <%= link_to image_tag("createone.svg"),new_post_url, method: :get %> </span> </li>      <li class="navigation-bar-right"> <span class="home"> <%= link_to image_tag("home.svg"), posts_url, data: {no_turbolink: true} %> </span> </li>      <li class="navigation-bar-right" id="drop"> <span class="settings"> <a href="#"> <img class="#" src="/assets/settings.svg"> </a> </span>        <ul class="dropdown">          <li> <%= link_to "Profile", edit_user_registration_path, method: :get %> </li>          <li> <%= link_to "Log out", destroy_user_session_url, method: :delete %> </li>           </ul>      </li>   </div>    </ul>   

posts.js.coffee

jQuery ->  $("#drop").click (e) ->    e.preventDefault()    $(this).find(".dropdown").fadeToggle "fast"    $(document).on "click", (e) ->    $trigger = undefined    $trigger = $("#drop")    $(".dropdown").fadeOut "fast"  if $trigger isnt e.target and not $trigger.has(e.target).length  

CSS

ul li .dropdown {    display: none;    position: fixed;    z-index:100;     margin-top: -8px;  }    .dropdown li {    list-style-type: none;    padding: 8px;    width: 70px;    font-size: 11px;    font-family: helvetica;   }  

NGINX file not found for php files

Posted: 15 Mar 2016 04:05 AM PDT

I have the following setup.

Nginx as a web server. Passing request to unicorn which runs as my ruby on rails server. I now want to install wordpress at mysite.com/blog. I therefore have installed and configured php and fastcgi. The nginx config is as follows:

upstream unicorn_mysite {    server unix:/tmp/unicorn.mysite.sock fail_timeout=0;  }    server {   listen 80;   server_name mysite.com;   return 301 https://www.$server_name$request_uri;  }    server {    listen 443 ssl;    ssl_certificate /opt/certs/thinbundle.crt;    ssl_certificate_key /opt/certs/mysite.key;    server_name mysite.com;      root /opt/www/mysite/current/public;      location /blog {             index index.php;               if (!-e $request_filename) {             rewrite  ^(.*)$  /blog/index.php?q=$1  last;                                        }                    location ~ .php(?|$) {                     include /etc/nginx/fastcgi_params;                     fastcgi_index index.php;                     fastcgi_param SCRIPT_FILENAME /opt/www/mysite_wordpress$fastcgi_script_name;                     fastcgi_pass unix:/var/run/php5-fpm.sock;                  }    }        location ~ ^/assets/ {      gzip_static on;      expires max;      add_header Cache-Control public;    }      try_files $uri/index.html $uri @unicorn;    location @unicorn {      proxy_set_header Host $http_host;        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;      proxy_redirect off;      proxy_pass http://unicorn_mysite;      proxy_set_header X-Forwarded-Proto $scheme;      add_header Front-End-Htps on;    }      error_page 500 502 503 504 /500.html;    client_max_body_size 4G;    keepalive_timeout 10;  }  

and the fastcgi_params file in /etc/nginx/fastcgi_params contains:

fastcgi_param  QUERY_STRING       $query_string;  fastcgi_param  REQUEST_METHOD     $request_method;  fastcgi_param  CONTENT_TYPE       $content_type;  fastcgi_param  CONTENT_LENGTH     $content_length;    fastcgi_param  SCRIPT_NAME        $fastcgi_script_name;  fastcgi_param  REQUEST_URI        $request_uri;  fastcgi_param  DOCUMENT_URI       $document_uri;  fastcgi_param  DOCUMENT_ROOT      $document_root;  fastcgi_param  SERVER_PROTOCOL    $server_protocol;  fastcgi_param  REQUEST_SCHEME     $scheme;  fastcgi_param  HTTPS              $https if_not_empty;    fastcgi_param  GATEWAY_INTERFACE  CGI/1.1;  fastcgi_param  SERVER_SOFTWARE    nginx/$nginx_version;    fastcgi_param  REMOTE_ADDR        $remote_addr;  fastcgi_param  REMOTE_PORT        $remote_port;  fastcgi_param  SERVER_ADDR        $server_addr;  fastcgi_param  SERVER_PORT        $server_port;  fastcgi_param  SERVER_NAME        $server_name;    # PHP only, required if PHP was built with --enable-force-cgi-redirect  fastcgi_param  REDIRECT_STATUS    200;  

When I go to mysite.com/blog I get this :

enter image description here

When I look at the nginx logs I see:

2016/03/15 11:26:35 [error] 23109#23109: *29 FastCGI sent in stderr: "Primary script unknown" while reading response header from upstream, client: 185.14.209.183, server: mysite.com, request: "GET /blog HTTP/1.1", upstream: "fastcgi://unix:/var/run/php5-fpm.sock:", host: "www.mysite.com"  2016/03/15 11:28:36 [error] 23109#23109: *35 FastCGI sent in stderr: "Primary script unknown" while reading response header from upstream, client: 185.14.209.183, server: mysite.com, request: "GET /blog HTTP/1.1", upstream: "fastcgi://unix:/var/run/php5-fpm.sock:", host: "www.mysite.com"  2016/03/15 11:32:12 [error] 23109#23109: *38 FastCGI sent in stderr: "Primary script unknown" while reading response header from upstream, client: 185.14.209.183, server: mysite.com, request: "GET /blog HTTP/1.1", upstream: "fastcgi://unix:/var/run/php5-fpm.sock:", host: "www.mysite.com"  2016/03/15 11:36:41 [error] 23109#23109: *45 FastCGI sent in stderr: "Primary script unknown" while reading response header from upstream, client: 185.14.209.183, server: mysite.com, request: "GET /blog HTTP/1.1", upstream: "fastcgi://unix:/var/run/php5-fpm.sock:", host: "www.mysite.com"  

Can somebody please help me fix this File not found. Which file is not found? and where is it looking for it - i.e why can't it find it! None of these errors help me identify the cause of the issue!

Creating rails new app takes too long

Posted: 15 Mar 2016 04:40 AM PDT

I'm new to Ror and I'm facing a problem while creating new rails app by using this command:

$ rails new test_app

it takes so long to execute it in bundle install process

Ps. I installed rails by using rbenv

gem ver: 2.4.5.1

ruby ver: ruby 2.2.3p173 (2015-08-18 revision 51636) [x86_64-linux]

rails ver: Rails 4.2.4

bundler ver: 1.10.6

How to make a User signed_in from controller using devise and rails 3.2?

Posted: 15 Mar 2016 04:00 AM PDT

I am trying to make user signed_in from controller. I used below code in controller

sign_in(:user, @user)  

Using this I got current_user on same page. But on second page I didn't gate current_user.

Please help me!!

Use cookies.signed[:user_id] in capybara tests

Posted: 15 Mar 2016 04:28 AM PDT

I have this code to authenticate channel subscribers:

module ApplicationCable    class Connection < ActionCable::Connection::Base      identified_by :current_user        def connect        self.current_user = find_verified_user      end        protected        def find_verified_user          if current_user = User.find_by(id: cookies.signed[:user_id])            current_user          else            reject_unauthorized_connection          end        end    end  end  

And everything works fine. The problem is in feature tests. When I run this test:

require 'rails_helper'    feature 'Chat room' do    scenario "send one message" do      user = create(:user)      login_as(user, :scope => :user)        expect {        fill_in 'message', with: 'hello friend'        click_button 'Send'        byebug      }.to change(Message, :count).by(1)      expect(current_path).to eq root_path      expect(page).to have_content 'hello friend'    end  end  

The test log, says that the "An unauthorized connection attempt was rejected". Since the cookie is empty, it is not able to authenticate.

So how can I set the cookies in capybara tests?

I tried something do this cookies.signed[:user_id] = user.id in the test but it does not work.

How can I set the cookie like this cookies.signed[:user_id] = user.id in tests?

Generating PDF out of HTML template using flying_ruby_saucer gem in rails

Posted: 15 Mar 2016 05:26 AM PDT

My requirement is I am generating PDF out of the pre-rendered HTML template. This template is a multi-lingual page and uses custom fonts from our clients.

Following approaches tried:

  • I used wicked_pdf (internally uses wkhtmltopdf-binary) gem to achieve this, but the issues I face are: font kerning arent proper as every other character get overlapped on other. The same font appears proper on actual PDF. I included all CSSes directly into the HEAD -> STYLE, tried various tricks by setting letter-spacing, etc. but nothing worked.

  • So, now using flying_ruby_saucer. Font kerning looks proper. But neither characters from Arabic OR HINDI is printed on PDF nor custom font is picked up. I have declared custom font as:

    @font-face {    font-family: 'My Font';    src: url('http://localhost:3000/assets/MyFont.ttf');  }  body{ font-family:"My Font"; }  

But this doesnot work either as PDF generated shows default font family. Non-ascii characters arent printed too.

Could anyone please help me fixing this (include foreign characters as well as include custom fonts)?

Thanks.

Construct NET::HTTP header files

Posted: 15 Mar 2016 03:49 AM PDT

I am required to make an http request with a header similar to the one quoted below.

POST /approval HTTP/1.1  Content-Type:text/xml  Content-Length:569  Host:127.0.0.1  Authorization: WSSE realm="SDP", profile="UsernameToken"  X-WSSE: UsernameToken Username="xxxxxxxxxxxxxxx", PasswordDigest=" xxxxxxxxxxxxxxxx", Nonce=" xxxxxxxxxxxxxx", Created="2012-07-26T11:31:26Z"  X-RequestHeader: request ServiceId="xxxxxxxxxxxxx", TransId=" xxxxxxxxxxxxxxxxxxx" , LinkId="xxxxxxxxxx", FA="xxxxxxxxxx"  Cookie: sessionid=default8fcee064690b45faa9f8f6c7e21c5e5a  Msisdn: 861111111  X-HW-Extension: k1=v1;k2=v2  <ns2:preapprovalrequest xmlns:ns2="http://www.xxxxxxxx.com">  <fromfri>ID:2341305205559/MSISDN</fromfri>  <tofri>ID:2341305205559/MSISDN</tofri>  <message>abc</message>  </ns2:preapprovalrequest>  

I have attempted to make the Net::HTTP Ruby 2.2.0 library with something similar to this.

url = 'http://xxx.xxx.xxx.xxx:xx/xxx/xxx/approval'  request_xml = "<?xml version='1.0' encoding='UTF-8'?><ns2:approvalrequest xmlns:ns2='http://www.xxxxxxxx.com'><fromfri></fromfri><tofri></tofri><message></message></ns2:approvalrequest>"  uri = URI(url)  req = Net::HTTP::Post.new(uri.path)  req.content_type = 'text/xml'  req['Authorization']['/']="WSSE"  req['Authorization']['realm']= "xxxxx"  req['Authorization']['profile']="xxxxxxxx"  req['X-WSSE']['/']="UsernameToken"  req['X-WSSE']['Username']=""  req['X-WSSE']['PasswordDigest']=""  req['X-WSSE']['Nonce']=""  req['X-WSSE']['Created']=""  req['X-RequestHeader']['/']="request"  req['X-RequestHeader']['ServiceId']=""  req['X-RequestHeader']['TransId']=""  req['X-RequestHeader']['LinkId']=""  req['X-RequestHeader']['FA']=""  req.body = request_xml  response = Net::HTTP.start(uri.hostname, uri.port) {|http|    http.request(req)  }  result = Hash.from_xml(response.body)  

However, this throws errors. Any idea how to construct a proper header file with multiple fields.

DEPRECATION WARNING: ref is deprecated and will be removed from Rails 3.2

Posted: 15 Mar 2016 03:48 AM PDT

I am using ruby 1.9.3p392 (2013-02-22 revision 39386) [x86_64-linux] and Rails 3.1.12

I need to fix this DEPRECATION WARNING

Can anyone had same issue?

DEPRECATION WARNING: ref is deprecated and will be removed from Rails 3.2. (called from <top (required)> at /home/hitesh/Desktop/projects/myapp/config/application.rb:7)    DEPRECATION WARNING: new is deprecated and will be removed from Rails 3.2. (called from <top (required)> at /home/hitesh/Desktop/projects/myapp/config/application.rb:7)    /home/hitesh/.rvm/gems/ruby-1.9.3-p392/gems/activesupport-3.1.12/lib/active_support/dependencies.rb:240:in `block in require': iconv will be deprecated in the future, use String#encode instead.  development  

ActiveRecord and multi threading problems with sessions

Posted: 15 Mar 2016 05:20 AM PDT

I use in my RoR project threads for getting data from Db (Vertica, Cassandra). Like this:

  def show      @lock = Mutex.new         tr=Thread.new{        @lock.synchronize {          @data_manager.problem_metadata(@problem_type)        }      }        tr = tr.value        tr.map do       # etc      end  end  

But after running this method I see, that the number of sessions in DB grows and I don't know why! Probably, I have to kill all threads after running my method or something else. Help me please to fix this problem, because in case of having sessions count >50 my app stopps.

New Rails app error - HOME environment variable must be set

Posted: 15 Mar 2016 03:40 AM PDT

I have installed RoR from http://railsinstaller.org/ru-RU
My system is Windows 7 x86
When i try to create new app using "rails new test_app" i get this error:

/D:/RailsInstaller/Ruby2.1.0/lib/ruby/site_ruby/2.1.0/rbreadline.rb:1097:in `': HOME environment variable (or HOMEDRIVE and HOMEPATH) must be set and point to a directory (RuntimeError)

How can I fix this? I already found a topic with the same problem, but it didn't help me.

1 comment:

  1. Many thanks for your kind invitation. I’ll join you.
    Would you like to play cards?
    Come to the party with me, please.
    See you soon...

    คาสิโนออนไลน์

    คาสิโน

    เครดิตฟรี

    คาสิโน

    ReplyDelete