Tuesday, September 6, 2016

The gem wkhtmltopdf and pdfkit in a Rails app on Heroku produces an error | Fixed issues

The gem wkhtmltopdf and pdfkit in a Rails app on Heroku produces an error | Fixed issues


The gem wkhtmltopdf and pdfkit in a Rails app on Heroku produces an error

Posted: 06 Sep 2016 08:08 AM PDT

I have a rails 3.2 app on heroku and these 2 gems:

ruby "2.2.4"  gem 'rails', '3.2.16'    # .......  gem 'wkhtmltopdf-binary-11'  gem 'pdfkit'  

However, when I'm trying to generate pdf, I get the following errors:

QSslSocket: cannot resolve SSLv2_client_method  QPixmap: Cannot create a QPixmap when no GUI is being used  

Obviously, I can't install a library or update it on heroku to fix the errors. How to fix them? And the same kind of error I have locally, but I'm on Arch.

Rails 4 Error: ActiveRecord::RecordNotFound Couldn't find 'id'=

Posted: 06 Sep 2016 08:04 AM PDT


Hey,
I'm fairly new to rails and into coding my first app. Just can't figure out how to target a user the current_user favorited (Three models: User, Tool, FavoriteUser).

Controller (Tools)

def index    @favorites = current_user.favorites.order("created_at DESC")    @userfavorites = current_user.userfavorites.order("created_at DESC")    @tools = Tool.where(user_id: current_user).order("created_at DESC")    @user = FavoriteUser.find(params[:c_user_id]).user_id    @cuser = current_user  end  

Index View (Tools)

%h2 My Favorite Users  - @userfavorites.each do |user|      = image_tag gravatar_for @user if @user.use_gravatar == true      = image_tag @user.avatar_filename.url if @user.use_gravatar == false      %h2= link_to @user.username, @user      %p= link_to "Favorite", @userfavorite_user_path(user, type: "favorite"), method: :get      %p= link_to "Unfavorite", @userfavorite_user_path(user, type: "unfavorite"), method: :get  

If I run this in my browser it appears following error:

ActiveRecord::RecordNotFound in ToolsController#index  Couldn't find FavoriteUser with 'id'=  

I simply can't figure it out.

Thanks in advance for your help!

Rails Cookies to manipulate database entries

Posted: 06 Sep 2016 07:51 AM PDT

I am trying to create a rails app and I have a database consisting of author and a quotation by that author. Now different users can choose to destroy or kill quotations from the database however it must only be deleted for that particular user i.e other users should still be able to see quotes that they didn't delete even if another user did. I know that I would need to implement cookies but other than that I am unsure how to proceed. Can anyone point me to a tutorial or give me some pointers to get started on this complex task? Thank you PS: New to rails!!!

Turbolinks loads Javascript multiple times

Posted: 06 Sep 2016 07:50 AM PDT

I'm using Turbolinks 2.5.3 and I have a script tag at the bottom of the home page.

<script>    $(document).ready(function() {      alert('hello');    });  </script>  

For every page on the site, I run the following JS:

Turbolinks.pagesCached(0);  

If I visit the home page, the alert appears once. If I press the back button then forward button on my browser the home page will load, and now two alerts appear. If I repeat this process again, three alerts will appear.

Here's my question:

Why is Turbolinks caching the page when I explicitly told it not to. Does it have to do with Turbolinks transforming the document ready event listener? How do I fix this so it only loads once every time?

EER diagram for a Rails app

Posted: 06 Sep 2016 07:48 AM PDT

I have a rails app. I am trying to reverse engineer an EER diagram with a few selected tables. For example, these 2 tables:

create_table "fee_parameters", force: :cascade do |t|    t.integer  "fee_type_id",    limit: 4    t.string   "name",           limit: 255    t.string   "value",          limit: 255    t.string   "parameter_type", limit: 255    t.datetime "created_at",                 null: false    t.datetime "updated_at",                 null: false  end    create_table "fee_rules", force: :cascade do |t|    t.integer  "fee_suite_id",     limit: 4    t.integer  "fee_parameter_id", limit: 4    t.string   "name",             limit: 255    t.float    "multiplier",       limit: 24    t.float    "addend",           limit: 24    t.datetime "created_at",                   null: false    t.datetime "updated_at",                   null: false  end  

In Workbench, when I click on the 1:1 icon and select these 2 tables then inside the fee_rules table is generated a fee_parameters_id. But I already have that foreign key. It's called fee_parameter_id. How do I let Workbench know this is the case?

Restarting delayed_job in production

Posted: 06 Sep 2016 07:41 AM PDT

I attempt to restart my delayed_job worker like so:

  task :restart_dj do      on roles(:app) do          execute "RAILS_ENV=production #{File.join(current_path,'bin','delayed_job')} restart"      end    end  

Unfortunately, I get this:

 DEBUG [64a01587] Command: /usr/bin/env ln -s /home/me/rails/dino/releases/20160906142152 /home/me/rails/dino/releases/current    INFO [64a01587] Finished in 0.177 seconds with exit status 0 (successful).    INFO [713c695b] Running /usr/bin/env mv /home/me/rails/dino/releases/current /home/me/rails/dino as me@91.16.120.84   DEBUG [713c695b] Command: /usr/bin/env mv /home/me/rails/dino/releases/current /home/me/rails/dino    INFO [713c695b] Finished in 0.349 seconds with exit status 0 (successful).    INFO [7c2e9550] Running RAILS_ENV=production /home/me/rails/dino/current/bin/delayed_job restart as me@91.16.120.84   DEBUG [7c2e9550] Command: RAILS_ENV=production /home/me/rails/dino/current/bin/delayed_job restart   DEBUG [7c2e9550]   /home/me/rails/dino/releases/20160906142152/config/boot.rb:1:in `<top (required)>'   DEBUG [7c2e9550]   :   DEBUG [7c2e9550]   undefined local variable or method `__dir__' for main:Object   DEBUG [7c2e9550]    (   DEBUG [7c2e9550]   NameError   DEBUG [7c2e9550]   )   DEBUG [7c2e9550]       from /home/me/rails/dino/releases/20160906142152/config/application.rb:1:in `require_relative'   DEBUG [7c2e9550]       from /home/me/rails/dino/releases/20160906142152/config/application.rb:1:in `<top (required)>'   DEBUG [7c2e9550]       from /home/me/rails/dino/current/config/environment.rb:2:in `require_relative'   DEBUG [7c2e9550]       from /home/me/rails/dino/current/config/environment.rb:2:in `<top (required)>'   DEBUG [7c2e9550]       from /usr/lib/ruby/1.9.1/rubygems/custom_require.rb:36:in `require'   DEBUG [7c2e9550]       from /usr/lib/ruby/1.9.1/rubygems/custom_require.rb:36:in `require'   DEBUG [7c2e9550]       from /home/me/rails/dino/current/bin/delayed_job:3:in `<main>'  

However, I can run RAILS_ENV=production bin/delayed_job restart on my production console with no issue.

I'm using Ruby 2.3.1.

Creating some class during tests (STI)

Posted: 06 Sep 2016 07:53 AM PDT

I have a class

Gate < ActiveRecord::Base    self.inheritance_column = :kindof  # some methods  end  #  and derived  MoneyHaters < Gate  # some overloaded methods  end  

with type column :kindof for STI.

Durning tests I want to create a 2-3 childs. Mainly because each derived class must be unique in the app. Like that:

factory :gate do    before(:create) do      gate_name  = FFaker::Company.name.gsub( /\s+/,'' )      gate_class_name = gate_name.singularize.classify    end      name { gate_name }      # I want that next class will be declared in App namespace, like all others.    gate_class  = Class.new(Gate) do      def comission_in(amount)        amount * 0.01 + 5      end      def comission_out(amount)        amount * 0.02 + 5      end    end    Object.const_set( gate_class_name, gate_class )      type { gate_class_name }    country { FFaker::Address.country_code }  end  

Code gave me error when ran with rspec in line "Object.const_set"

TypeError: #<FactoryGirl::Declaration::Implicit:0x00000006a1af30 @name=:gate_class_name, @ignored=false, @factory=#<FactoryGirl::Definition:0x00000006ed6df8 @declarations=#<FactoryGirl::DeclarationList:0x00000006ed6dd0 @declarations=[#<FactoryGirl::Declaration::Dynamic:0x00000006ed6998 @name=:name, @ignored=false, @block=#<Proc:0x00000006ed69c0@[skipped]>>, #<FactoryGirl::Declaration::Implicit:0x00000006a1af30 ...>], @name=:gate, @overridable=false>, @callbacks=[#<FactoryGirl::Callback:0x00000006ed6a38 @name=:before_create, @block=#<Proc:0x00000006ed6ba0@[skipped]>>], @defined_traits=#<Set: {}>, @to_create=nil, @base_traits=[], @additional_traits=[], @constructor=nil, @attributes=nil, @compiled=false>> is not a symbol nor a string  

but works ok in rails console

Usually I call FactoryGirl factories for creating objects, but, if that is impossible - I wonder for any other method to do that.

Any help is very much appreciate.

disable ActionController::InvalidAuthenticityToken only for json request?

Posted: 06 Sep 2016 07:15 AM PDT

I know this question have been asked in this forum. but it did not work for me.

my requirement is something like this

     if request.type.json?         #disbale `ActionController::InvalidAuthenticityToken`       else       # enable `ActionController::InvalidAuthenticityToken`       end  

any idea !! how to achieve this??

Rails model - NameError: uninitialized constant

Posted: 06 Sep 2016 07:01 AM PDT

I have two models:

app/models/data_science/field_of_studies_job_titles.rb

module DataScience    class FieldOfStudiesJobTitle < ActiveRecord::Base      self.table_name = 'ds_campus_transitions_disciplines_current'      self.primary_keys = :fieldofstudy, :jobrole    end  end  

app/models/field_of_studies_job_title.rb

class FieldOfStudiesJobTitle < ActiveRecord::Base    belongs_to :job_title    belongs_to :field_of_study      validates :job_title_id, uniqueness: { scope: :field_of_study_id }      def self.import(source)      source.find_in_batches do |batch|      batch.each do |item|        puts "huhu"      end    end  end  

In rails console:

bundle exec rails c  Loading development environment (Rails 4.2.7)  irb(main):001:0> FieldOfStudiesJobTitle.import(::DataScience::FieldOfStudiesJobTitle)  NameError: uninitialized constant DataScience::FieldOfStudiesJobTitle      from (irb):1      from /usr/local/bundle/gems/railties-4.2.7/lib/rails/commands/console.rb:110:in `start'      from /usr/local/bundle/gems/railties-4.2.7/lib/rails/commands/console.rb:9:in `start'      from /usr/local/bundle/gems/railties-4.2.7/lib/rails/commands/commands_tasks.rb:68:in `console'      from /usr/local/bundle/gems/railties-4.2.7/lib/rails/commands/commands_tasks.rb:39:in `run_command!'      from /usr/local/bundle/gems/railties-4.2.7/lib/rails/commands.rb:17:in `<top (required)>'      from bin/rails:4:in `require'      from bin/rails:4:in `<main>'  irb(main):002:0>  

Why I get this error message ?

I know it happens when the rails environment is not loaded with the file of the class for which the method was called.

But why it happens in this particular case ?

How i can set values in a f.text_field?

Posted: 06 Sep 2016 07:47 AM PDT

I was trying to set value to a f.text_field but I am unable to set the value

This is my code:

<%= f.label :example %><br>  <%= f.text_field :example, :value => 'example' %>  

working with a celluloid pool

Posted: 06 Sep 2016 06:45 AM PDT

I have a model with chat's id. And I need do get all messages for each chat via https request and store them to my bd. There are about 3000 chats for a day

I want to create a rake task for it with celluloid pool, something like this:

require 'celluloid/current'    namespace :db do        desc "get messages for chats"      task get_messages: :environment do          get_messages        end  end    def get_messages      bot = Admin.first      pool = Loader.pool(size: 10, args: [bot.login, bot.pwd])      ids_to_get_mes = bot.chats.without_messages.map{|x| x.id}        ids_to_get_mes.each do |chat_id|          pool.async.save_mes(chat_id)          end  end  

This part will call remoute url, send request and get a response

@inf.request(:chat_messages, chat_id: chat_id)  

and i have a Loader class for that.

class Loader      include Celluloid          finalizer :shutdown        def initialize(login, pwd)          @inf = Inf.new(:login => login, :password => pwd)      end        def shutdown          self.terminate      end       def request_messages(chat_id)          @inf.request(:chat_messages, chat_id: chat_id)      end        def save_mes(chat_id)          request_messages(chat_id).each do |message|              MessageSaveWorker.perform_async(message)          end      end  end  

and i have a sidekiq worker MessageSaveWorker just for saving data

I am trying to rake this task and get messages only for first 10 chats, and then error massage

ERROR -- : Couldn't cleanly terminate all actors in 10 seconds!

How can i fix it and get messages for all chats from array?

Reset DB from Controller/Helper, Ruby on Rails

Posted: 06 Sep 2016 07:58 AM PDT

I've created a demo of my program. The demo is used to present the program to the customers. Before each presentation I want to reset the db, and insert certain data, the actions that I have to do are:

rake db:drop  rake db:setup  rake db:seed:demo  

But they are not always me to present it and others do not use the console, so I wanted to put in the settings page the ability to reset via a button.

I tried in this way:

module SettingsHelper  require 'rake'    def reset          Rake::Task[db:drop].invoke          Rake::Task[db:setup].invoke          Rake::Task[db:seeds:demo].invoke    end  end  

I put in the form:

  <%=button_to "Reset", reset, class:"btn red" %>  

But I can not drop the database with the active server ... how can I do?

How to speed up rails first time byte [on hold]

Posted: 06 Sep 2016 06:06 AM PDT

So i've got my web application running fine, I'm just looking to speed it up.

For some reason my css is taking a long time to load?

What would be the best way to speed this up? along with other speed tips?

Heres the results of the test in detail https://www.webpagetest.org/result/160906_A8_KHV/

Also is 7 seconds long for a web page load?

Thanks

Rspec feature test. Page content doesn't differ among ordinary user and admin

Posted: 06 Sep 2016 06:02 AM PDT

I'm new to testing. I use rspec-rails, factory_girl_rails and capybara to test Rails 5 app. For authentication I have devise.

My User model has additional field admin. By default admin is false. But first registered user becomes an administrator (user.admin = true).

Now when I do user = create(:user) in my test it creates an 'ordinary' user (user.admin = false)

But if I puts page.body I can see content which should not be rendered for an ordinary user.

Here is my template:

%menu   %ul     - if user_signed_in?       %li         Hey, #{current_user.name}       %li= link_to "Edit Profile", edit_user_registration_path       - if current_user.admin         %li= link_to "Today's Orders", todays_orders_path         %li= link_to "Registered Users", users_path         %li= link_to "Add Dish", new_dish_path       %li= link_to "Sign Out", destroy_user_session_path  

Feature test's snippet:

require 'rails_helper'  require_relative '../support/authentication'    feature 'page content' do      let(:user) { create(:user) }      scenario 'show page content' do      authentication = Authentication.new user      authentication.sign_in        puts page.body    end  end  

That's what puts return:

<menu>  <ul>  <li>  Hey, Test User  </li>  <li><a href="/users/edit">Edit Profile</a></li>  <li><a href="/todays_orders">Today&#39;s Orders</a></li>  <li><a href="/users">Registered Users</a></li>  <li><a href="/dishes/new">Add Dish</a></li>  <li><a href="/users/sign_out">Sign Out</a></li>  </ul>  </menu>  

I suppose current_user.admin is ignored or something. But how to make it work properly?

my controller spec on email confirmation fails

Posted: 06 Sep 2016 06:57 AM PDT

Here Im testing email confirmation fails. In dev mode everything works just ok. And I think that I've missed some configurations.

context 'with valid provider data' do    before { session["devise.provider_data"] = { provider: 'twitter', uid: '123456' } }    it "sends email confirmation" do      expect{ post :create, authorization: { email: "user@email.com" } }.to change(ActionMailer::Base.deliveries, :count).by(1)    end  end  

And the error

Failure/Error: expect{ post :create, authorization: { email: "user@email.com" } }.to change(ActionMailer::Base.deliveries, :count).by(1)     expected #count to have changed by 1, but was changed by 0  

Coul anybody help with this?

context 'with valid provider data' do    before { session["devise.provider_data"] = { provider: 'twitter', uid: '123456' } }    before(:each) do      ActionMailer::Base.delivery_method = :test      ActionMailer::Base.perform_deliveries = true      ActionMailer::Base.deliveries = []    end      after(:each) do      ActionMailer::Base.deliveries.clear    end      it "sends email confirmation" do      expect{ post :create, authorization: { email: "user@email.com" } }.to change(ActionMailer::Base.deliveries, :count).by(1)    end  end  

How to only show dropdown options for @user?

Posted: 06 Sep 2016 06:33 AM PDT

Currently all the challenge records are being listed in the dropdown instead of just the challenges for the chosen @user.

duels/_dueler_fields.html.erb

<%= f.select :user_id, User.order(:name).map { |user| [user.full_name, user.id] }, include_blank: true, id: "change-challenge-options" %> # After a user is chosen, only the challenges for that user should be listed from the partial below      will    <%= render :partial => 'user_challenges', locals: {challenges: Challenge.order(:created_at)} %> # should only list challenges from :user_id    <script>  $( "#change-challenge-options" ).change(function() {       $.ajax({          type: "GET",          url: '<%= user_challenges_path %>', # replace by your route          data: {name: $('#id_of_the_user_id_select_box').prop('value')}       });  });  </script>  

duels/_user_challenges.html.erb

<div id="dropdown-no-2">     <%= collection_select(:challenge, :challenge_id, challenges, :id, :full_challenge, include_blank: true) %>.  </div>  

duels/user_challenges.html.erb

$("#dropdown-no-2").html('<%=j render :partial => "user_challenges", locals: {challenges: @challenges} %>');   

duels_controller.rb

  def user_challenges      @user = User.find(params[:id])      @challenges = @user.challenges.order(:created_at)    end      def new      @duel = Duel.new      @duel.duelers << Dueler.new(user_id: current_user.id, user_name: current_user.name, user_last_name: current_user.last_name)      @duel.duelers << Dueler.new(user: User.find(15), challenge: Challenge.find(158))      respond_with(@duel)     end  

routes.rb

get 'duels/user_challenges', :to => 'duels#user_challenges', as: 'user_challenges'  

Scroll event doesn't work unless the page is reloaded

Posted: 06 Sep 2016 05:50 AM PDT

I'm looking to set a "scroll up" button using JQuery for my rails application. Here's the JQuery script:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>  <script type="text/javascript">      $(function() {          $(window).scroll(function() {              if($(this).scrollTop() > 300) {                  $('#toTop').fadeIn();              } else {                  $('#toTop').fadeOut();              }          });          $('#toTop').click(function() {              $('body,html').animate({scrollTop:0},300);          });      });  </script>  

Here's CSS for the button:

#toTop {      width:100px;      text-align:center;      padding:5px;      position:fixed;      bottom:5px;      left:50%;      cursor:pointer;      display:none;      color:#333;      font-size:20px;      &:hover {        color:  #8B0000;      }  }  

When I open a new page, say localhost:3000/signup, the button scrolls up just fine. But if I click on another page, the scroll event doesn't happen. Thus, the button works properly either if I reload the page or open a new one in another tab. What might cause the problem?

RAILS Add trigger into a migration

Posted: 06 Sep 2016 07:13 AM PDT

I use mysql in a rails app and i want to create a trigger, but with a migration. This is my sql code

DELIMITER ;;  CREATE TRIGGER check_validation_participant  BEFORE UPDATE ON participants  FOR EACH ROW  BEGIN    DECLARE valide INTEGER;      IF NEW.current_state = 1 THEN        SELECT COUNT(*) INTO valide      FROM participants      WHERE user_id = NEW.user_id      AND current_state = 1;          IF valide > 0 THEN          SIGNAL SQLSTATE '45000'              SET MESSAGE_TEXT = 'Un événement est déjà validé pour cet utilisateur';      END IF;  END IF;  END;;  

In migration i write this code into execute "..." but i have a lot of syntax errors. Thank you :)

unable to integrate open_id_authentication with ActionController::API

Posted: 06 Sep 2016 04:29 AM PDT

I am buidling rails application with my ApplicationController building on ActionController::API. I tried integrating open_id_authentication gem and it worked fine if my ApplicationController was built using ActionController::Base but threw error with API. I tried including middleware in following manners

Method 1. Add middleware in initilaizer

    `config/initializers/openid.rb`       require 'open_id_authentication'       Rails.application.config do        config.middleware.use OpenIdAuthentication          config.after_initialize do          OpenID::Util.logger = Rails.logger          ActionController::API.send :include,  OpenIdAuthentication::ControllerMethods        end       end  

but got following error stack with it:

        NoMethodError - undefined method `authenticate_with_open_id' for #:        app/controllers/v2/sessions_controller.rb:45:in `accounts_authentication'        app/controllers/v2/sessions_controller.rb:17:in `login'        actionpack (4.2.6) lib/action_controller/metal/implicit_render.rb:4:in `send_action'        actionpack (4.2.6) lib/abstract_controller/base.rb:198:in `process_action'        actionpack (4.2.6) lib/action_controller/metal/rendering.rb:10:in `process_action'        actionpack (4.2.6) lib/abstract_controller/callbacks.rb:20:in `block in process_action'        activesupport (4.2.6) lib/active_support/callbacks.rb:117:in `call'        activesupport (4.2.6) lib/active_support/callbacks.rb:555:in `block (2 levels) in compile'        activesupport (4.2.6) lib/active_support/callbacks.rb:505:in `call'        activesupport (4.2.6) lib/active_support/callbacks.rb:92:in `__run_callbacks__'        activesupport (4.2.6) lib/active_support/callbacks.rb:778:in `_run_process_action_callbacks'        activesupport (4.2.6) lib/active_support/callbacks.rb:81:in `run_callbacks'        actionpack (4.2.6) lib/abstract_controller/callbacks.rb:19:in `process_action'        actionpack (4.2.6) lib/action_controller/metal/rescue.rb:29:in `process_action'        actionpack (4.2.6) lib/action_controller/metal/instrumentation.rb:32:in `block in process_action'        activesupport (4.2.6) lib/active_support/notifications.rb:164:in `block in instrument'        activesupport (4.2.6) lib/active_support/notifications/instrumenter.rb:20:in `instrument'        activesupport (4.2.6) lib/active_support/notifications.rb:164:in `instrument'        actionpack (4.2.6) lib/action_controller/metal/instrumentation.rb:30:in `process_action'        activerecord (4.2.6) lib/active_record/railties/controller_runtime.rb:18:in `process_action'        actionpack (4.2.6) lib/abstract_controller/base.rb:137:in `process'        actionview (4.2.6) lib/action_view/rendering.rb:30:in `process'        actionpack (4.2.6) lib/action_controller/metal.rb:196:in `dispatch'        actionpack (4.2.6) lib/action_controller/metal/rack_delegation.rb:13:in `dispatch'        actionpack (4.2.6) lib/action_controller/metal.rb:237:in `block in action'        actionpack (4.2.6) lib/action_dispatch/routing/route_set.rb:74:in `dispatch'        actionpack (4.2.6) lib/action_dispatch/routing/route_set.rb:43:in `serve'        actionpack (4.2.6) lib/action_dispatch/journey/router.rb:43:in `block in serve'        actionpack (4.2.6) lib/action_dispatch/journey/router.rb:30:in `serve'        actionpack (4.2.6) lib/action_dispatch/routing/route_set.rb:817:in `call'        rack-openid (1.4.2) lib/rack/openid.rb:98:in `call'        rack (1.6.4) lib/rack/etag.rb:24:in `call'        rack (1.6.4) lib/rack/conditionalget.rb:25:in `call'        rack (1.6.4) lib/rack/head.rb:13:in `call'        actionpack (4.2.6) lib/action_dispatch/middleware/params_parser.rb:27:in `call'        actionpack (4.2.6) lib/action_dispatch/middleware/flash.rb:260:in `call'        rack (1.6.4) lib/rack/session/abstract/id.rb:225:in `context'        rack (1.6.4) lib/rack/session/abstract/id.rb:220:in `call'        actionpack (4.2.6) lib/action_dispatch/middleware/cookies.rb:560:in `call'        activerecord (4.2.6) lib/active_record/query_cache.rb:36:in `call'        activerecord (4.2.6) lib/active_record/connection_adapters/abstract/connection_pool.rb:653:in `call'        activerecord (4.2.6) lib/active_record/migration.rb:377:in `call'        actionpack (4.2.6) lib/action_dispatch/middleware/callbacks.rb:29:in `block in call'        activesupport (4.2.6) lib/active_support/callbacks.rb:88:in `__run_callbacks__'        activesupport (4.2.6) lib/active_support/callbacks.rb:778:in `_run_call_callbacks'        activesupport (4.2.6) lib/active_support/callbacks.rb:81:in `run_callbacks'        actionpack (4.2.6) lib/action_dispatch/middleware/callbacks.rb:27:in `call'        actionpack (4.2.6) lib/action_dispatch/middleware/reloader.rb:73:in `call'        actionpack (4.2.6) lib/action_dispatch/middleware/remote_ip.rb:78:in `call'        better_errors (2.1.1) lib/better_errors/middleware.rb:84:in `protected_app_call'        better_errors (2.1.1) lib/better_errors/middleware.rb:79:in `better_errors_call'        better_errors (2.1.1) lib/better_errors/middleware.rb:57:in `call'        actionpack (4.2.6) lib/action_dispatch/middleware/debug_exceptions.rb:17:in `call'        web-console (2.3.0) lib/web_console/middleware.rb:20:in `block in call'        web-console (2.3.0) lib/web_console/middleware.rb:18:in `call'        actionpack (4.2.6) lib/action_dispatch/middleware/show_exceptions.rb:30:in `call'        railties (4.2.6) lib/rails/rack/logger.rb:38:in `call_app'        railties (4.2.6) lib/rails/rack/logger.rb:20:in `block in call'        activesupport (4.2.6) lib/active_support/tagged_logging.rb:68:in `block in tagged'        activesupport (4.2.6) lib/active_support/tagged_logging.rb:26:in `tagged'        activesupport (4.2.6) lib/active_support/tagged_logging.rb:68:in `tagged'        railties (4.2.6) lib/rails/rack/logger.rb:20:in `call'        actionpack (4.2.6) lib/action_dispatch/middleware/request_id.rb:21:in `call'        rack (1.6.4) lib/rack/methodoverride.rb:22:in `call'        rack (1.6.4) lib/rack/runtime.rb:18:in `call'        activesupport (4.2.6) lib/active_support/cache/strategy/local_cache_middleware.rb:28:in `call'        rack (1.6.4) lib/rack/lock.rb:17:in `call'        actionpack (4.2.6) lib/action_dispatch/middleware/static.rb:120:in `call'        railties (4.2.6) lib/rails/engine.rb:518:in `call'        railties (4.2.6) lib/rails/application.rb:165:in `call'        rack (1.6.4) lib/rack/lock.rb:17:in `call'        rack (1.6.4) lib/rack/content_length.rb:15:in `call'        rack (1.6.4) lib/rack/handler/webrick.rb:88:in `service'        /usr/local/rvm/rubies/ruby-2.3.1/lib/ruby/2.3.0/webrick/httpserver.rb:140:in `service'        /usr/local/rvm/rubies/ruby-2.3.1/lib/ruby/2.3.0/webrick/httpserver.rb:96:in `run'    

Method 2. Add middleware via config/environment/development.rb

          require 'open_id_authentication'       Rails.application.configure do        config.middleware.use OpenIdAuthentication::Middleware       end    

It gave the same error stack

Please help me with the solution to include middleware for open_id_authentication in ActionController::API

Globalize gem: how to keep track of translations?

Posted: 06 Sep 2016 04:12 AM PDT

I want to translate some models in my Rails app using Globalize gem. This seems pretty easy, but I wonder how it's best to keep track of changed texts? So that I don't forget to update all other translations after I changed one of them?

Is there some feature for this already built in? So I can see which fields of my model have changed in the meantime compared to some translation, and then I can do the translations and fix them as done?

Also, when I just fix a typo, I don't want the translation to be seen as "changed".

SOLR: Can changes in synonyms.txt file take effect without reindex?

Posted: 06 Sep 2016 05:09 AM PDT

we are using Sunspot-solr 4.0 when i update synonyms file it does not change anything in search. Do i really need to re-index after making changes in synonyms.txt or there is any other trick to update synonyms file that i am missing?

Ruby regex for domains

Posted: 06 Sep 2016 05:06 AM PDT

I am looking for a domain validator regex which validates domain. Preferably I want to use some inbuilt regex using URI::Regexp.

Domain scheme and protocol are optional. It should validate all domains of type

abc.com, abc.cm, ab.com/aka/jaka, abc.aio.com

It should invalidate domains of type abc, abc. jska

ember uploader authentication help please

Posted: 06 Sep 2016 05:30 AM PDT

I am trying to upload an image to a rails API from an ember app. I have installed the ember uploader addon and my URL is correct (works perfectly through postman), but I am having problems with authentication.

The app itself is set up with devise and the routes all have authenticatedRouteMixin and the adaptors have the dataAdaptorMixin which automatically take care of the authentication.

I am struggling to inject authentication into the the call to the API. Any help would be appreciated. My call to the API currently looks like this. An extra argument can go at (files[0],{extraArgument}) but not sure if this is even where I should be putting authentication details or how to access them.

export default EmberUploader.FileField.extend({      filesDidChange: function(files) {      const uploader = EmberUploader.Uploader.create({        url: this.get('url'),        method: 'PUT',          });        if (!Ember.isEmpty(files)) {        data with the upload        uploader.upload(files[0]);      }    }  });  

PS. An additional problem I have is that the url needs to be supplied however I need to be supplying the id of the models so it knows where to go, any suggestions on how to dynamically make the URL would also be appreciated

Display PDF's uploaded with paperclip

Posted: 06 Sep 2016 04:32 AM PDT

I upload files (PDF's only) using paperclip and now want to display these as a PDF in a view.

This gives me an empty frame <iframe src="<% @document.file %>"></iframe> This results in an image <%= image_tag @document.file(:large) %>

the files are stored in postgress.

IE browser Date Time Issue

Posted: 06 Sep 2016 03:42 AM PDT

On IE 11 browser the below statement is returning an invalid date response: new Date("2016-03-09T22:40:05.653-0800"). Where as on the chrome/firefox it is returning the valid date.

Please suggest me !!

Heroku not installing private gem locally

Posted: 06 Sep 2016 05:45 AM PDT

I have an issue with installing a private gem on heroku. I have managed to install it once, with the oauth token, and the deploy goes just as it should. The Gemfile line goes like this:

gem 'personal_gem', "0.0.3", git: "https://TOKEN:x-oauth-basic@github.com/personal_gem.git", branch: :master  

It all goes as planned the first time around. I go back to my project all happy, make a few changes and then deploy again. And I get this amazing message:

Running: bundle install --without development:test --path vendor/bundle --binstubs vendor/bundle/bin -j4 --deployment  remote: /tmp/build_b69276ed81314bd83fe154e89deceb82/vendor/ruby-2.2.4/lib/ruby/2.2.0/rubygems/dependency.rb:315:in 'to_specs': Could not find 'personal_gem' (>= 0) among 159 total gem(s) (Gem::LoadError)`  

Boom.

I believe I've tried it all. Bumping up the gem version, all the "git", "github" combinations in the Gemfile I could think of.

Heroku gem list does NOT list the gem!

Heroku bundle install DOES list the gem.

On my machine, installations go just fine. There are no local gem installations of this gem to conflict with the one I'm pushing online, it shows the github link properly.

The most bizarre thing is that the first install goes as it should. Also, if I change the ruby version and push, it also goes just fine. But not on subsequent pushes on the same ruby version.

I'm under impression that for some reason the gem isn't installed on heroku. However, the site + gem functionality work as intended online.

This is some X-Files stuff here, and any help/pointers are really appreciated!

sanitize and raw still showing html tags, Slim

Posted: 06 Sep 2016 05:37 AM PDT

I have a comment data which contains html text, and I want to show the html renders without any tags inside.

I'm working with RoR and slim.

I tried sanitize, raw and html_safe. but all of them gave me the same result. they removed some html but I still see html tags.

data before using them:

&lt;img alt=&quot;User-added image&quot; src=&quot;https://rrrrr;amp;feoid=00N2400000H7Rxb&amp;amp;refid=0EM7E0000004FgN&quot; style=&quot;height: 333px; width: 500px;&quot;&gt;&lt;/img&gt;&lt;br&gt;&lt;br&gt;Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam   

data after using them:

    = raw resource.comments      = sanitize resource.comments      = strip_tags "'#{resource.comments}'"      = ActionView::Base.full_sanitizer.sanitize(resource.comments)  

or

def formatted_comments    h.sanitize(comments, :tags => [], :attributes => [])  end      = formatted_comments  

result:

<img alt="User-added image" src="https://rrrrr;feoid=00N2400000H7Rxb&amp;refid=0EM7E0000004FgN" style="height: 333px; width: 500px;"></img><br><br>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam   

Update:

I noticed that the rendered html tag contains the following. " my result of html tags here " = $0 trying to remove it manually, all html was rendered!

Condition exist array id with id in rails

Posted: 06 Sep 2016 04:56 AM PDT

I have query :

Product.all.where(x: @id)  

With

x = ["9", "8", "7","5"] # Array exam    # And     @id = 5   

How to check if 5 is in array?

Rails gem for shared static pages

Posted: 06 Sep 2016 03:18 AM PDT

I have a core gem which is used by two applications. Inside the core gem I have the public directory, which contains a few static pages(error pages etc.). How can I make the static pages accessible through the applications?

For instance the core gem has the static page test.html inside the public directory and I want to access test.html through application 1 using www.application1.com/test.html as url.

Thanks!

Ruby on rails Simple Search not displaying results

Posted: 06 Sep 2016 05:12 AM PDT

Hey guys im developing a rails application that stores quotes in a database and then allows you to search through the quotes using a simple search. I have implemented the search form but the results do not appear and I cant figure out why.

controller:

class BasicsController < ApplicationController    def quotations      @quotations = Quotation.all      if params[:search]        @quotations = Quotation.search(params[:search]).order("created_at DESC")      else        @quotations = Quotation.all.order("created_at DESC")      end        if params[:quotation]        @quotation = Quotation.new( params[:quotation] )        if @quotation.save          flash[:notice] = 'Quotation was successfully created.'          @quotation = Quotation.new        end      elsif        @quotation = Quotation.new      end      if params[:sort_by] == "date"        @quotations = Quotation.order(:created_at)      else        @quotations = Quotation.order(:category)      end    end  end  

model:

class Quotation < ApplicationRecord    def self.search(search)      where("author_name LIKE ? OR quote LIKE ?", "%#{search}", "%#{search}")    end  end  

view:

<%= form_tag basics_quotations_path, :method => 'get' do %>  <p>  <%= text_field_tag :search, params[:search], placeholder: "Search    Quotations" %>    <%= submit_tag "Search", :name => nil %>  </p>  <% end %>  <h3>Quotations</h3>  <ul>  <% for quotation in @quotations %>    <li><%= h quotation.author_name %>: <%= h quotation.quote %></li>  <% end %>  </ul>  <br/>  <% if params[:sort_by] == "date" %>  <%= link_to "Sort by category", :action => :quotations, :sort_by =>    :category %>  <% else %>  <%= link_to "Sort by date", :action => :quotations, :sort_by => :date %>  <% end %>  <hr/>    <h3>New quotation</h3>  <%= form_for @quotation, :url => { :action => :quotations } do |form| %>  <fieldset>    <legend>Enter details</legend>    <div class="form_row">      <%= form.label :author_name %>      <%= form.text_field :author_name, :size => 20, :maxlength => 40 %>    </div>    <div class="form_row">      <%= form.label :category %>      <% @cats = [] %>      <% Quotation.select('DISTINCT category').map(&:category).each do |element| %>          <% @cats << element %>      <% end %>      <%= form.select(:category,options_for_select([[@cats[0],1],[@cats[1], 2], [@cats[2],3]])) %>    </div>    <div class="form_row">      <%= form.label :new_category%>      <%= form.text_field :category , :size =>20 , :maxlength => 40 %>    </div>    <div class="form_row">      <%= form.label :quote %>      <%= form.text_area :quote, :rows => 2, :cols => 40, :maxlength => 500 %>    </div>  </fieldset>  <p>  <div class="form_row">    <%= form.submit 'Create' %>  </div>  </p>  <% end %>  

routes: Rails.application.routes.draw do get 'basics/quotations' resources :quotation, :quotations # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html end

No comments:

Post a Comment