Thursday, December 1, 2016

Is it possible to generate a fake Braintree Client Token or VCR the request? | Fixed issues

Is it possible to generate a fake Braintree Client Token or VCR the request? | Fixed issues


Is it possible to generate a fake Braintree Client Token or VCR the request?

Posted: 01 Dec 2016 07:45 AM PST

I have an integration/feature spec in my Spree Rails app that already VCR records the final payment request. However, I can notice still the external call to Braintree to calculate the client token.

I looked in the docs and I did not see a test object that I could use when it generates the token.

Is it possible to either have a test object that will provide a test Braintree client token? Or is it just better to VCR record that initial request?

IntelliJ IDEA / RubyMine - Run multiple rake tasks at once?

Posted: 01 Dec 2016 07:43 AM PST

In a terminal, I can run multiple rake tasks one after another in a single line:

rake grunt war app_server:start  

I can't seem to get this to work in IntelliJ IDEA when trying to create a Configuration to do it. I'm able to fill in the "Task Name" field as above, but when I run the configuration, I get the following error:

Don't know how to build task 'grunt war app_server:start' (see --tasks)  

Does anyone know if I'm just doing something wrong, or is this just not possible in IDEA? Thank you.

Rails 5 routing resources using custom actions

Posted: 01 Dec 2016 07:42 AM PST

About routing, If I do something like this:

resources :students  resources :teachers  

I will get something like:

students GET /students(.:format) students#index
...
teachers GET /teachers(.:format) teachers#index
...

Changing to:

resources :students, controller: :users  resources :teachers, controller: :users  

will give me:

students GET /students(.:format) users#index
teachers GET /teachers(.:format) users#index

Note that now, both resources are using the same controller Users and the same action index. But what I need, instead of using the same index action, is the students resource to use actions prefixed by students like students_index and teachers resources prefixed by teachers like teacher_index.

In other words, I want bin/rails routes to give me the following output:

students GET /students(.:format) users#students_index
teachers GET /teachers(.:format) users#teachers_index

I know that I can do the same with:

get 'students', to: 'users#students_index'  

But there is a way to do the same with resources?

pundit returning incorrect values

Posted: 01 Dec 2016 07:47 AM PST

I have this Application Policy:

class ApplicationPolicy    attr_reader :user, :record      def initialize(user, record)      @user = user      @record = record    end      ...          def create?      user && user.admin?    end      def update?      create?    end      def edit?      create?    end  end  

PostPolicy looks something like this:

class PostPolicy < ApplicationPolicy    ...    def create?      super     end    def update?      super    end    def edit?      super    end    ...  end  

Now when a user that is not admin i.e user returns true (it exists) and user.admin? returns false (it is not an admin) tries to edit or update a post we check the application policy. We would now expect that when the user tries to edit a post it would get access denied since update? returns super.update? and super.update? returns super.create? which should return false.

This is not the case. If we print user && user.admin? inside of ApplicationPolicy's create? it prints out false if we then print out create? inside update? it prints out true. I tried doing a fast check without pundit but that worked as expected

I have now solved this simply by changing the body of update? to:

def update?    user && user.admin?  end  

Inside ApplicationPolicy which solves my problem. So I guess I'm mostly curious why this would happen and if someone has encountered the same issue.

Rails: field_with_errors styling not being applied to WYSIWYG input field

Posted: 01 Dec 2016 07:40 AM PST

I am using the trix WYSIWYG text editor on an input field.

The user fails a validation and the form gets re-rendered. What should happen is that the label gets styled red and the input field gets a red border due to field_with_errors. Here is what is actually happening:

input field does not have red border

As you can see: the label is properly getting styled red, but the input field is not getting the red border.

Here is the html of the input after failing validation:

html of input

So we see that field_with_errors is properly wrapping both the label and the input field. However, the styling for field_witih_errors is simply being ignored for the input field.

Question: How can I get my field_witih_errors styling to apply to an input field which is using the trix WYSIWYG?

Getting "can't create Thread: Resource temporarily unavailable" since I started using Capybara::Poltergeist

Posted: 01 Dec 2016 06:49 AM PST

I recently added some code that uses Capybara::Poltergeist to fetch information from pages that work with JavaScript. (I'll be happy to replace it with a something else if there is an option)

The I load the page , input some data into it , click a button , wait for return value.

In order to try and have as little memory leaks , zombie processes etc. I use the following:

Capybara.default_driver         = :poltergeist  Capybara.default_max_wait_time  = 60  Capybara.javascript_driver      = :poltergeist    Capybara.register_driver :poltergeist do |app|    Capybara::Poltergeist::Driver.new(app, {js_errors: false} )  end    capybara_session                = Capybara::Session.new(:poltergeist , timeout: 60 )  

I do some actions .....

capybara_session.try(:reset_session!)  capybara_session.try(:driver).try(:quit)  Capybara.try(:drivers).try(:clear)  

But I'm still getting "can't create Thread: Resource temporarily unavailable" after a few hours of operation.

Any idea how to solve or replace this?

How to create a hash for all records created by a user?

Posted: 01 Dec 2016 06:47 AM PST

In our Rails app, the user (or we on his behalf) load some data or even insert it manually using a crud.

After this step the user must validate all the configuration (the data) and "accept and agree" that it's all correct.

On a given day, the application will execute some tasks according the configuration.

Today, we already have a "freeze" flag, where we can prevent changes in the data, so the user cannot mess the things up...

But we also would like to do something like hash the data and say something like "your config is frozen and the hash is 34FE00...".

This would give the user a certain that the system is running with the configuration he approved.

How can we do that? There are 7 or 8 tables. The total of records created would be around 2k or 3k.

How to hash the data to detect changes after the approval? How would you do that?

I'm thinking about doing a find_by_user in each table, loop all records and use some fields (or all) to build a string and hash it at the end of the current loop.

After loop all tables, I would have 8 hash strings and would concatenate and hash them in a final hash.

How does it looks like? Any ideas?

sunspot_rails gem - Search for giving model considering parent's relationships

Posted: 01 Dec 2016 06:43 AM PST

Considering the following models:

class State < ApplicationRecord  end    class City < ApplicationRecord    belongs_to :state  end    class Neighbourhood < ApplicationRecord    belongs_to :city      searchable do      text :name        text :city_name do        city.name      end        text :state_abbreviation do        city.state.abbreviation      end    end  end  

And my search method (Neighbourhood's Controller):

class Admin::NeighbourhoodsController < ApplicationController    def search(q)      Neighbourhood.search do        fulltext q      end.results    end  end  

I would like do use sunspot solr gem to search for Neighbourhoods considering it's name, city_name (direct belongs_to relationship) and state name (City's belongs_to relationship).

Is it possible to search for models considering parent's relationships?

Using Amoeba to copy a page with blocks and contents

Posted: 01 Dec 2016 06:41 AM PST

I have the following model for my Pages in my rails app:

class Page < ActiveRecord::Base      has_many :blocks    has_many :contents, :through => :blocks      amoeba do      enable      include_association :blocks      include_association :contents    end      def create_branch      branch = self.amoeba_dup #should dup content and blocks too      branch.branched_from = self.id #so we know what record it was copied from      branch.status = 0 #set this new copy to draft      branch.save #save the branch      branch #return the branch    end    end  

So a Page has Blocks, and Blocks have Contents.

The models for them are as follows:

class Block < ActiveRecord::Base    belongs_to :page    belongs_to :block_template    has_many :contents  end    class Content < ActiveRecord::Base    belongs_to :block  end  

What I want to do is when I'm calling this in my controller:

  def branch      @page = Page.find(params[:id])      @branch = @page.create_branch      redirect_to edit_page_path(@branch), :notice => 'Draft created!'    end  

It will duplicate the Page and its Blocks and Contents. I'm using the Amoeba gem to duplicate the associations as well.

However if I put a break point on @branch, it looks to have all the data but doesn't have an ID, so the redirect fails. It doesn't have an ID because it hasn't be properly duplicated... any ideas why?

It should be creating copies of the Page, Blocks, and Content.

I tried the clone method like clone: [:blocks, :contents] but that gave me an error that clone takes 0 parameters...

Error R14 (Memory quota exceeded) + Heroku + Passenger

Posted: 01 Dec 2016 06:35 AM PST

2016-12-01T14:26:14.421530+00:00 heroku[run.6714]: Error R14 (Memory quota exceeded)  2016-12-01T14:25:51+00:00 app[heroku-redis]: source=REDIS sample#active-connections=1 sample#load-avg-1m=0.07 sample#load-avg-5m=0.09 sample#load-avg-15m=0.075 sample#read-iops=0 sample#write-iops=0 sample#memory-total=15664468.0kB sample#memory-free=11956144.0kB sample#memory-cached=2248760.0kB sample#memory-redis=1421856bytes sample#hit-rate=1 sample#evicted-keys=0  2016-12-01T14:26:35.660410+00:00 heroku[run.6714]: Process running mem=780M(152.4%)  2016-12-01T14:26:35.660501+00:00 heroku[run.6714]: Error R14 (Memory quota exceeded)  

I'm getting above error on heroku logs. I don't understand the solution and why this error occur.

My server confirmation is high -

  1. Professional Dynos
  2. 2X Worker
  3. Premium Redis Plan - ($15)
  4. Database is - Standard 4 Plan

But still getting this error

rails ActiveRecord can you merge scopes that have joins within them?

Posted: 01 Dec 2016 06:55 AM PST

I am wanting to join a single table to another table with a specific scope.

What I had tried to do does not work, but a version using sub-select works correctly.

MyModel belongs_to a User class (which has_one MyModel) and the user class has a scope that involves joins to other tables.

What I am trying to do is:

# doesn't work, gives user that is not inside the merged scope  MyModel.joins(:user).merge(User.has_accounts)  

This generates the following SQL which I think should do what I want:

SELECT DISTINCT "my_model".* FROM  "my_model" INNER JOIN "users" ON "users"."id" =   "my_model"."user_id" LEFT OUTER JOIN "logins" ON   "logins"."user_id" = "users"."id" LEFT OUTER JOIN "logins"   "logins_users_join" ON "logins_users_join"."user_id" = "users"."id"   LEFT OUTER JOIN "accounts" ON "accounts"."login_id" =   "logins_users_join"."id"  

The user scope "has_accounts" has some joins inside it:

scope :has_accounts, -> { joins(:logins).joins(:accounts).distinct }  

I am able to write write the query correctly using a sub-select like so:

# works does not give my_model that has a user associated that is not in the scope  MyModel.where(user_id: User.has_accounts.select(:id))  

The relevant parts of the model are as follows:

class MyModel    belongs_to :user  end    class User    has_one :my_model    has_many :logins    has_many :accounts, through: :logins    scope :has_accounts, -> { joins(:logins).joins(:accounts).distinct }  end    class Login    belongs_to :user    has_many :accounts  end    class Account    belongs_to :login  end  

what am I doing wrong with my join and merge so that it does not give the correct result?

Can anyone see what it is in the generated SQL that means that the users that do not have an associated account are present in the result?

Cron parameter in not working in sidekiq rails

Posted: 01 Dec 2016 06:59 AM PST

I have been implemented sidekiq-cron in my rails application. I want to run scheduled task using this gem.

Here is yml file config/schedule.yml :

    message_worker:        class: MessageWorker        queue: default        cron: "* * * * * *"  

Here is my worker class:

    class MessageWorker        include Sidekiq::Worker        sidekiq_options retry: 2, backtrace: true        def perform()          # Here is my business logic        end      end  

Here I loading all my task in initializer file:

    require 'sidekiq'      require 'sidekiq-cron'      require 'sidekiq/web'        redis_config = YAML.load_file("config/redis.yml")      redis_config.merge! redis_config.fetch(Rails.env, {})      redis_config.symbolize_keys!        Sidekiq.configure_server do |config|        config.redis = { url: "redis://localhost:6379/" }        puts "redis started"      end        Sidekiq.configure_client do |config|        config.redis = { url: "redis://localhost:6379/" }        puts "configure client"     end     schedule_file = "config/schedule.yml"       if File.exists?(schedule_file) && Sidekiq.server?       sidekiq_cron = YAML.load_file(schedule_file)       Sidekiq::Cron::Job.load_from_hash sidekiq_cron     end  

When I run sidekiq server using bundle ex sedikiq it throws me below exception:

    2016-12-01T14:08:36.916Z 12150 TID-orgj0i010 ERROR: CRON JOB: can't convert Rufus::Scheduler::ZoTime into an exact number        2016-12-01T14:08:36.916Z 12150 TID-orgj0i010 ERROR: CRON JOB: /home/user/.rvm/gems/ruby-2.3.0@<gemset-name>/gems/activesupport-4.2.7.1/lib/active_support/core_ext/time/calculations.rb:233:in `-'  

How Can I resolve this problem?

retrieving multiple association data with conditions

Posted: 01 Dec 2016 06:17 AM PST

I've been a programmer for a few years (I've mainly used PHP / CakePHP) but I'm new to Ruby on Rails.

I have a question regarding retrieving data for multiple associations with conditions.

I have the following four models:

class Questionnaire < ApplicationRecord    has_many :sections  end    class Section < ApplicationRecord    belongs_to :questionnaire    has_many :questions    has_many :non_questions      def elements      (questions + non_questions).sort_by(&:order)    end    end    class Question < ApplicationRecord    belongs_to :section      validates_date :starts_on, allow_blank: true    validates_date :expires_on, allow_blank: true  end    class NonQuestion < ApplicationRecord      belongs_to :section  end  

I currently want to show the whole questionnaire in the view - that is all the sections with their questions and non_questions in one page and in the right order. I would also like to pass a date parameter from the view, which will be used to retrieve the corresponding active questions only, based on the starts_on and expires_on date columns.

Using CakePHP, I would preload and store all the data in a variable in my model by using Left Joins with conditions. I tried to do something similar with rails (using all possible combinations of joins, includes, left_outer_joins) with a where condition, but when I, for example, call questionnaire.sections.first.elements it runs a new query without applying my condition. Am I missing something out? Is there a "right", ruby way to do something like this? Or given what my application requires, is there a better way to approach this?

Thanks in advance

Reduce/tweak excessive queries to make rails app faster

Posted: 01 Dec 2016 05:42 AM PST

It takes a while for a page reload.. Tried using bullet gem but not getting any logs.. I have posted some of the excessive queries i make to the database and i know its suboptimal and looking to tweak it. How can I tweak it? I have posted my index action too

def index      @customer = Customer.new      # Search Customer query    @search = Customer.ransack(params[:q])     @c = @search.result(distinct: true).desc_order.limit(4)      # Get all rooms     @rooms = Room.all      # Get all Room Categories    @room_types = RoomCategory.all    @recent_bookings = BookRoom.all.order("created_at DESC")    @recent_bills = BillContainer.all.order("created_at DESC")      #  Search Booked rooms query     @search2 = BookRoom.ransack(params[:q])     @bill_conts = @search2.result(distinct: true).desc_order    end    Customer Load (1.0ms)  SELECT  DISTINCT "customers".* FROM "customers" ORDER BY created_at DESC LIMIT $1  [["LIMIT", 4]]      Rendered customers/_form.html.erb (3.5ms)      BillContainer Load (0.6ms)  SELECT "bill_containers".* FROM "bill_containers" ORDER BY created_at DESC       (0.5ms)  SELECT SUM("bills"."deposit") FROM "bills" WHERE "bills"."bill_container_id" = $1  [["bill_container_id", 27]]       (0.9ms)  SELECT SUM("bills"."bill_price") FROM "bills" WHERE "bills"."bill_container_id" = $1  [["bill_container_id", 27]]       (0.5ms)  SELECT SUM("bills"."deposit") FROM "bills" WHERE "bills"."bill_container_id" = $1  [["bill_container_id", 26]]       (0.6ms)  SELECT SUM("bills"."bill_price") FROM "bills" WHERE "bills"."bill_container_id" = $1  [["bill_container_id", 26]]       (0.6ms)  SELECT SUM("bills"."deposit") FROM "bills" WHERE "bills"."bill_container_id" = $1  [["bill_container_id", 25]]       (0.6ms)  SELECT SUM("bills"."bill_price") FROM "bills" WHERE "bills"."bill_container_id" = $1  [["bill_container_id", 25]]       (0.6ms)  SELECT SUM("bills"."deposit") FROM "bills" WHERE "bills"."bill_container_id" = $1  [["bill_container_id", 24]]       (0.6ms)  SELECT SUM("bills"."bill_price") FROM "bills" WHERE "bills"."bill_container_id" = $1  [["bill_container_id", 24]]       (0.6ms)  SELECT SUM("bills"."deposit") FROM "bills" WHERE "bills"."bill_container_id" = $1  [["bill_container_id", 23]]       (0.5ms)  SELECT SUM("bills"."bill_price") FROM "bills" WHERE "bills"."bill_container_id" = $1  [["bill_container_id", 23]]       (0.7ms)  SELECT SUM("bills"."deposit") FROM "bills" WHERE "bills"."bill_container_id" = $1  [["bill_container_id", 22]]       (0.5ms)  SELECT SUM("bills"."bill_price") FROM "bills" WHERE "bills"."bill_container_id" = $1  [["bill_container_id", 22]]       (0.5ms)  SELECT SUM("bills"."deposit") FROM "bills" WHERE "bills"."bill_container_id" = $1  [["bill_container_id", 21]]       (0.5ms)  SELECT SUM("bills"."bill_price") FROM "bills" WHERE "bills"."bill_container_id" = $1  [["bill_container_id", 21]]       (0.6ms)  SELECT SUM("bills"."deposit") FROM "bills" WHERE "bills"."bill_container_id" = $1  [["bill_container_id", 20]]       (0.6ms)  SELECT SUM("bills"."bill_price") FROM "bills" WHERE "bills"."bill_container_id" = $1  [["bill_container_id", 20]]       (0.6ms)  SELECT SUM("bills"."deposit") FROM "bills" WHERE "bills"."bill_container_id" = $1  [["bill_container_id", 19]]       (0.6ms)  SELECT SUM("bills"."bill_price") FROM "bills" WHERE "bills"."bill_container_id" = $1  [["bill_container_id", 19]]       (0.5ms)  SELECT SUM("bills"."deposit") FROM "bills" WHERE "bills"."bill_container_id" = $1  [["bill_container_id", 18]]       (0.4ms)  SELECT SUM("bills"."bill_price") FROM "bills" WHERE "bills"."bill_container_id" = $1  [["bill_container_id", 18]]       (0.4ms)  SELECT SUM("bills"."deposit") FROM "bills" WHERE "bills"."bill_container_id" = $1  [["bill_container_id", 17]]       (0.4ms)  SELECT SUM("bills"."bill_price") FROM "bills" WHERE "bills"."bill_container_id" = $1  [["bill_container_id", 17]]       (0.5ms)  SELECT SUM("bills"."deposit") FROM "bills" WHERE "bills"."bill_container_id" = $1  [["bill_container_id", 16]]       (0.6ms)  SELECT SUM("bills"."bill_price") FROM "bills" WHERE "bills"."bill_container_id" = $1  [["bill_container_id", 16]]       (0.7ms)  SELECT SUM("bills"."deposit") FROM "bills" WHERE "bills"."bill_container_id" = $1  [["bill_container_id", 15]]       (0.5ms)  SELECT SUM("bills"."bill_price") FROM "bills" WHERE "bills"."bill_container_id" = $1  [["bill_container_id", 15]]       (0.5ms)  SELECT SUM("bills"."deposit") FROM "bills" WHERE "bills"."bill_container_id" = $1  [["bill_container_id", 14]]       (0.5ms)  SELECT SUM("bills"."bill_price") FROM "bills" WHERE "bills"."bill_container_id" = $1  [["bill_container_id", 14]]       (0.5ms)  SELECT SUM("bills"."deposit") FROM "bills" WHERE "bills"."bill_container_id" = $1  [["bill_container_id", 13]]       (0.4ms)  SELECT SUM("bills"."bill_price") FROM "bills" WHERE "bills"."bill_container_id" = $1  [["bill_container_id", 13]]       (0.5ms)  SELECT SUM("bills"."deposit") FROM "bills" WHERE "bills"."bill_container_id" = $1  [["bill_container_id", 12]]       (0.4ms)  SELECT SUM("bills"."bill_price") FROM "bills" WHERE "bills"."bill_container_id" = $1  [["bill_container_id", 12]]       (0.4ms)  SELECT SUM("bills"."deposit") FROM "bills" WHERE "bills"."bill_container_id" = $1  [["bill_container_id", 11]]       (0.4ms)  SELECT SUM("bills"."bill_price") FROM "bills" WHERE "bills"."bill_container_id" = $1  [["bill_container_id", 11]]       (0.4ms)  SELECT SUM("bills"."deposit") FROM "bills" WHERE "bills"."bill_container_id" = $1  [["bill_container_id", 10]]       (0.4ms)  SELECT SUM("bills"."bill_price") FROM "bills" WHERE "bills"."bill_container_id" = $1  [["bill_container_id", 10]]       (0.4ms)  SELECT SUM("bills"."deposit") FROM "bills" WHERE "bills"."bill_container_id" = $1  [["bill_container_id", 9]]       (0.4ms)  SELECT SUM("bills"."bill_price") FROM "bills" WHERE "bills"."bill_container_id" = $1  [["bill_container_id", 9]]       (0.4ms)  SELECT SUM("bills"."deposit") FROM "bills" WHERE "bills"."bill_container_id" = $1  [["bill_container_id", 8]]       (0.4ms)  SELECT SUM("bills"."bill_price") FROM "bills" WHERE "bills"."bill_container_id" = $1  [["bill_container_id", 8]]       (0.5ms)  SELECT SUM("bills"."deposit") FROM "bills" WHERE "bills"."bill_container_id" = $1  [["bill_container_id", 7]]       (0.5ms)  SELECT SUM("bills"."bill_price") FROM "bills" WHERE "bills"."bill_container_id" = $1  [["bill_container_id", 7]]       (0.6ms)  SELECT SUM("bills"."deposit") FROM "bills" WHERE "bills"."bill_container_id" = $1  [["bill_container_id", 6]]       (0.5ms)  SELECT SUM("bills"."bill_price") FROM "bills" WHERE "bills"."bill_container_id" = $1  [["bill_container_id", 6]]       (0.7ms)  SELECT SUM("bills"."deposit") FROM "bills" WHERE "bills"."bill_container_id" = $1  [["bill_container_id", 5]]       (0.6ms)  SELECT SUM("bills"."bill_price") FROM "bills" WHERE "bills"."bill_container_id" = $1  [["bill_container_id", 5]]       (0.6ms)  SELECT SUM("bills"."deposit") FROM "bills" WHERE "bills"."bill_container_id" = $1  [["bill_container_id", 4]]       (0.6ms)  SELECT SUM("bills"."bill_price") FROM "bills" WHERE "bills"."bill_container_id" = $1  [["bill_container_id", 4]]       (0.5ms)  SELECT SUM("bills"."deposit") FROM "bills" WHERE "bills"."bill_container_id" = $1  [["bill_container_id", 3]]       (0.4ms)  SELECT SUM("bills"."bill_price") FROM "bills" WHERE "bills"."bill_container_id" = $1  [["bill_container_id", 3]]       (0.5ms)  SELECT SUM("bills"."deposit") FROM "bills" WHERE "bills"."bill_container_id" = $1  [["bill_container_id", 2]]       (0.4ms)  SELECT SUM("bills"."bill_price") FROM "bills" WHERE "bills"."bill_container_id" = $1  [["bill_container_id", 2]]       (0.6ms)  SELECT SUM("bills"."deposit") FROM "bills" WHERE "bills"."bill_container_id" = $1  [["bill_container_id", 1]]       (0.6ms)  SELECT SUM("bills"."bill_price") FROM "bills" WHERE "bills"."bill_container_id" = $1  [["bill_container_id", 1]]       Rendered customers/index.html.erb within layouts/application (276.5ms)       Room Load (0.5ms)  SELECT "rooms".* FROM "rooms"       ......... etc   

How can I get Current User Email in Redmine?

Posted: 01 Dec 2016 05:28 AM PST

I created plug in for Redmine using Ruby On Rails. In index.html.erb [View] I want information related logged in person .

<h2>ResourcemanagController#index</h2>    <%= User.current.name %>  <%= User.current.id %>  <% if User.current.admin? %>  Admin  <% end %>  

Using above code I am able to get User name , But I want email address of Current User. What to do ?

Ruby on Rails app can't query AWS - error 403 forbidden

Posted: 01 Dec 2016 05:18 AM PST

I was in a course last year to develop RoR applications. I developed one that searches AWS using my account's key and returns results. Now whenever I search Amazon I'm getting a 403 error.

I recreated my key and I've updated it in the Rails console but to no avail. How can I check my credentials or what else can I do to start hunting this problem down?

How to completely configure OmniAuth Shibboleth

Posted: 01 Dec 2016 05:16 AM PST

For a university project I made a rails app. Now my supervisor asked me to implement single sign on using OmniAuth Shibboleth. And asked me to come up with the requirements so that he can ask uni IT center to provide me with the required data.

After I finished reading the the documentation of OmniAuth and OmniAuth Shibboleth and also implemented OmniAuth twitter by watching a railscast just to know how omniauth works, I am still kind of lost.

For example consider the code below from the documentation page,

Rails.application.config.middleware.use OmniAuth::Builder do    provider :shibboleth, {      :shib_session_id_field     => "Shib-Session-ID",      :shib_application_id_field => "Shib-Application-ID",      :debug                     => false,      :uid_field                 => "uid",      :name_field                => "displayName",      :extra_fields => [        :"unscoped-affiliation",        :entitlement      ],      :info_fields => {        :email    => "mail",        :location => "contactAddress",        :image    => "photo_url",        :phone    => "contactPhone"      }    }  end  

Should I asked my uni IT center to provide these info? or after I sign in through Shibboleth I will get access these info?

Also there is a file shibd.conf: which should contain following code

<Location /application_path/auth/shibboleth/callback>    AuthType shibboleth    ShibRequestSetting requireSession 1    require valid-user  </Location>  

I dont know where to add this code.

And at last, I dont understand if my uni IT center will provide me a url, authentication token, metadata etc. What things shoudl I asked them to provide me.

And if they provide me with these info, where should I add them. In short, it would be nice if someone just give me a minimal working configuration for OmniAuth Shibboleth, including where to add login url, metadata, auth token etc.

Heroku send_file Supported (Rails 5)?

Posted: 01 Dec 2016 05:13 AM PST

https://devcenter.heroku.com/articles/rack-sendfile

Says that send_file is not supported, yet I am using it in a Rails app and it works perfectly.

Does anybody have any reference on whether send_file is now supported by Heroku or not?

How setting rvm in capistrano for Sinatra project

Posted: 01 Dec 2016 06:20 AM PST

I need in capistrano specify rvm for deploy Sinatra project to remote server

I have following deploy.rb

lock '3.4.0'    set :application, 'sudoku'  set :repo_url, 'git@github.com:user/name-project.git'    set :deploy_to, '/home/deploy/name-project'  set :linked_dirs, %w{ log }    namespace :deploy do      desc 'Restart application'    task :restart do      on roles(:app), in: :sequence, wait: 5 do        execute :touch, release_path.join('tmp/restart.txt')      end    end      after :publishing, 'deploy:restart'    after :finishing, 'deploy:cleanup'  end  

This is information about rvm on remote server

deploy@ubuntu-512mb-fra1-01:~$ rvm info        ruby-2.3.1:        homes:  gem:          "/home/deploy/.rvm/gems/ruby-2.3.1"  ruby:         "/home/deploy/.rvm/rubies/ruby-2.3.1"            environment:          PATH:         "/home/deploy/.rvm/gems/ruby-2.3.1/bin:/home/deploy/.rvm/gems/ruby-2.3.1@global/bin:/home/deploy/.rvm/rubies/ruby-2.3.1/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/home/deploy/.rvm/bin:/home/deploy/.rvm/bin"          GEM_HOME:     "/home/deploy/.rvm/gems/ruby-2.3.1"          GEM_PATH:     "/home/deploy/.rvm/gems/ruby-2.3.1:/home/deploy/.rvm/gems/ruby-2.3.1@global"          MY_RUBY_HOME: "/home/deploy/.rvm/rubies/ruby-2.3.1"          IRBRC:        "/home/deploy/.rvm/rubies/ruby-2.3.1/.irbrc"          RUBYOPT:      ""          gemset:       ""  

What me add in deploy.rb for setting RVM? Thank you

How do I validate nested attributes using reform + dry-validation?

Posted: 01 Dec 2016 05:11 AM PST

Validations are triggered and work as expected for attributes of the record I'm passing in (i.e required(:title).filled), but not for attributes of nested models (i.e required(:name).filled in artist).

class AlbumForm < Reform::Form    property :title      validation do     required(:title).filled    end      property :artist do      property :name        validation do       required(:name).filled      end    end  end  

(Snippet taken from http://trailblazer.to/gems/reform)

I expect Albumform.new(album).valid? to return false if album.artist.name == nil but it does not. What am I missing here? How can this be achieved?

Using:

  • rails 4.2.7.1
  • reform-rails 0.1.7
  • reform 2.2.2
  • dry-validation 0.10.3

Ruby on Rails messaging app updating clients

Posted: 01 Dec 2016 05:11 AM PST

I am creating a messaging app to try and learn more about RoR. I was originally hoping I could use ajax so that when a user sends a message, all the other users would be able to see that message appear without reloading. But as I'm seeing it now it seems a bit more complicated to do so. Could anyone confirm if this is possible or not using ajax, and if its not, what should I look at to make this work? Thanks

How to count empty range on csv files in one folder?

Posted: 01 Dec 2016 06:47 AM PST

Suppose I have 7 CSV files in one folder two of them are empty on [2..-1] range, how do I count them and get answer 2?

Getting this error when installing gems in aptana

Posted: 01 Dec 2016 04:34 AM PST

Getting this error when update/install gem Aptana radrails

ruby~$ ruby -v ruby 2.3.1p112 (2016-04-26 revision 54768) [i686-linux]

rails -v Rails 5.0.0


Welcome to the Rails Shell. This view is meant for advanced users and command line lovers as a text-based way to run rails commands such as: rails, script/generate, script/plugin, gem, rake, etc. This shell can replace the functionality of the Rake Tasks, Rails Plugins, and generators views.

gem install -l mongrel-1.1.5.gem ERROR: While executing gem ... (Gem::DependencyError) Unable to resolve dependencies: mongrel requires daemons (>= 1.0.3) gem install -l sqlite3-ruby-1.2.1.gem Building native extensions. This could take a while... ERROR: Error installing sqlite3-ruby-1.2.1.gem: ERROR: Failed to build gem native extension.

    /usr/bin/ruby1.9.1 extconf.rb /usr/lib/ruby/1.9.1/rubygems/custom_require.rb:36:in `require': cannot  

load such file -- mkmf (LoadError) from /usr/lib/ruby/1.9.1/rubygems/custom_require.rb:36:in require' from extconf.rb:1:in'

Gem files will remain installed in /var/lib/gems/1.9.1/gems/sqlite3-ruby-1.2.1 for inspection. Results logged to /var/lib/gems/1.9.1/gems/sqlite3-ruby-1.2.1/ext/sqlite3_api/gem_make.out

gem install -l linecache-0.43.gem Building native extensions. This could take a while... ERROR: Error installing linecache-0.43.gem: ERROR: Failed to build gem native extension.

    /usr/bin/ruby1.9.1 extconf.rb /usr/lib/ruby/1.9.1/rubygems/custom_require.rb:36:in `require': cannot  

load such file -- mkmf (LoadError) from /usr/lib/ruby/1.9.1/rubygems/custom_require.rb:36:in require' from extconf.rb:1:in'

Gem files will remain installed in /var/lib/gems/1.9.1/gems/linecache-0.43 for inspection. Results logged to /var/lib/gems/1.9.1/gems/linecache-0.43/ext/gem_make.out

gem install -l ruby-debug-base-0.10.3.gem ERROR: While executing gem ... (Gem::DependencyError) Unable to resolve dependencies: ruby-debug-base requires linecache (>= 0.3) gem install -l ruby-debug-ide-0.4.5.gem ERROR: While executing gem ... (Gem::DependencyError) Unable to resolve dependencies: ruby-debug-ide requires ruby-debug-base (~> 0.10.3.0)

Modify request url/path without redirect

Posted: 01 Dec 2016 06:18 AM PST

I'm trying to figure a way to modify my request URL before it's received by Puma.

Exemple:

User come on the site with a url like /locale/resource/:id. But I want him to be redirected to /locale/'resource/resource-slug because it's more pretty.

I've already made a first version of this.

before_action :redirect_with_pretty_challenge_url, only: %w(index show new edit)    private    def redirect_with_pretty_challenge_url    param_kind = challenge_show_or_admin_challenges? ? :id : :challenge_id    return unless params_is_id?(param_kind)      redirect_to stubbed_request_path_parameters(param_kind)  end    def params_is_id?(param_kind)    return true if params[param_kind].is_a?(Integer)      params[param_kind].to_i.to_s == params[param_kind]  end    def stubbed_request_path_parameters(param_kind)    request.path_parameters[param_kind] = Challenge.find_by_params(params[param_kind])&.slug    request.path_parameters  end  

So with this the user is redirected to the 'correct' url, but with a redirection...

I would like to know if there is a way to modify the url directly in the request so that I don't have to redirect_to the user, it will make this action way more 'transparent'.

Is it possible ? Or completely impossible due to the HTTP procotol ?

Could not find rake-11.3.0 on deployment (Capistrano Nginx Passenger)

Posted: 01 Dec 2016 05:30 AM PST

  • Recently updated an old web app to Rails 4.2.7.1 and Ruby 2.3.1 (It was working with Rails 3 and Ruby 1.9).
  • App running on an nginx-pasenger server on production with rvm.
  • Updated RVM and ruby in production, and set new ruby version as default.
  • Deployed with Capistrano.

The app is not working, from the nginx log:

[ 2016-12-01 07:00:34.0368 1509/7fbcbf7fe700 agents/HelperAgent/RequestHandler.h:2306 ]: [Client 20] Cannot checkout session because a spawning$  App 6899 stdout:  App 6899 stdout:  [ 2016-12-01 07:01:13.2625 1509/7fbccdf3b700 Pool2/Implementation.cpp:287 ]: Could not spawn process for application /home/deploy/porinstinto/c$    Error ID: 9864a1e8    Error details saved to: /tmp/passenger-error-NDJl0Z.html    Message from application: <p>It looks like Bundler could not find a gem. Maybe you didn't install all the gems that this application needs. T$      <pre class="commands">bundle install</pre>    <p>If that didn't work, then the problem is probably caused by your application being run under a different environment than it's supposed to. $    <ol>    <li>Is this app supposed to be run as the <code>deploy</code> user?</li>    <li>Is this app being run on the correct Ruby interpreter? Below you will        see which Ruby interpreter Phusion Passenger attempted to use.</li>    <li>Please check whether the correct RVM gemset is being used.</li>    <li>Sometimes, RVM gemsets may be broken.        <a href="https://github.com/phusion/passenger/wiki/Resetting-RVM-gemsets">Try resetting them.</a></li>  </ol>    <p>-------- The exception is as follows: -------</p>  Could not find rake-11.3.0 in any of the sources (Bundler::GemNotFound)  <pre>  /home/deploy/.rvm/gems/ruby-2.1.3@global/gems/bundler-1.7.3/lib/bundler/spec_set.rb:92:in `block in materialize&#39;    /home/deploy/.rvm/gems/ruby-2.1.3@global/gems/bundler-1.7.3/lib/bundler/spec_set.rb:85:in `map!&#39;    /home/deploy/.rvm/gems/ruby-2.1.3@global/gems/bundler-1.7.3/lib/bundler/spec_set.rb:85:in `materialize&#39;    /home/deploy/.rvm/gems/ruby-2.1.3@global/gems/bundler-1.7.3/lib/bundler/definition.rb:132:in `specs&#39;    /home/deploy/.rvm/gems/ruby-2.1.3@global/gems/bundler-1.7.3/lib/bundler/definition.rb:177:in `specs_for&#39;    /home/deploy/.rvm/gems/ruby-2.1.3@global/gems/bundler-1.7.3/lib/bundler/definition.rb:166:in `requested_specs&#39;    /home/deploy/.rvm/gems/ruby-2.1.3@global/gems/bundler-1.7.3/lib/bundler/environment.rb:18:in `requested_specs&#39;    /home/deploy/.rvm/gems/ruby-2.1.3@global/gems/bundler-1.7.3/lib/bundler/runtime.rb:13:in `setup&#39;    /home/deploy/.rvm/gems/ruby-2.1.3@global/gems/bundler-1.7.3/lib/bundler.rb:121:in `setup&#39;    /home/deploy/.rvm/gems/ruby-2.1.3@global/gems/bundler-1.7.3/lib/bundler/setup.rb:17:in `&lt;top (required)&gt;&#39;    /home/deploy/.rvm/rubies/ruby-2.1.3/lib/ruby/2.1.0/rubygems/core_ext/kernel_require.rb:135:in `require&#39;    /home/deploy/.rvm/rubies/ruby-2.1.3/lib/ruby/2.1.0/rubygems/core_ext/kernel_require.rb:135:in `rescue in require&#39;    /home/deploy/.rvm/rubies/ruby-2.1.3/lib/ruby/2.1.0/rubygems/core_ext/kernel_require.rb:144:in `require&#39;    /usr/lib/ruby/vendor_ruby/phusion_passenger/loader_shared_helpers.rb:263:in `block in run_load_path_setup_code&#39;    /usr/lib/ruby/vendor_ruby/phusion_passenger/loader_shared_helpers.rb:366:in `running_bundler&#39;    /usr/lib/ruby/vendor_ruby/phusion_passenger/loader_shared_helpers.rb:261:in `run_load_path_setup_code&#39;    /usr/share/passenger/helper-scripts/rack-preloader.rb:100:in `preload_app&#39;    /usr/share/passenger/helper-scripts/rack-preloader.rb:158:in `&lt;module:App&gt;&#39;    /usr/share/passenger/helper-scripts/rack-preloader.rb:29:in `&lt;module:PhusionPassenger&gt;&#39;    /usr/share/passenger/helper-scripts/rack-preloader.rb:28:in `&lt;main&gt;&#39;</pre>    [ 2016-12-01 07:01:13.2791 1509/7fbcbf7fe700 agents/HelperAgent/RequestHandler.h:2306 ]: [Client 20] Cannot checkout session because a spawning$  

How to unscope default_scope in join/eager_load?

Posted: 01 Dec 2016 05:18 AM PST

I have two models:

class User    default_scope -> { where(deleted_at: nil) }  end    class Order     belongs_to :user  end  

And I want to get orders with deleted or not deleted users:

Order.joins(:user).merge(User.unscoped)  Order.joins(:user).merge(User.unscope(where: :deleted_at))  # SELECT  "orders".* FROM "orders"   # INNER JOIN "users" ON "users"."id" = "orders"."user_id" AND "users"."deleted_at" IS NULL   # ORDER BY "orders"."id" DESC LIMIT 1    Order.eager_load(:user).merge(User.unscoped)  Order.eager_load(:user).merge(User.unscope(where: :deleted_at))  # SELECT  "orders"."id" AS t0_r0, "orders"."user_id" AS t0_r1,   # "users"."id" AS t1_r0, "users"."deleted_at" AS t1_r1 FROM "orders"   # LEFT OUTER JOIN "users" ON "users"."id" = "orders"."user_id" AND "users"."deleted_at" IS NULL   # ORDER BY "orders"."id" DESC LIMIT 1  

None of these work.

Every query adds "AND "users"."deleted_at" IS NULL" into join statement.

Nothing changes if I specify association scope:

class Order    belongs_to :user, -> { unscoped }   end  

However includes works as expected:

Order.includes(:user).merge(User.unscoped).last  # SELECT  "orders".* FROM "orders" ORDER BY "orders"."id" DESC LIMIT 1  # SELECT "users".* FROM "users" WHERE "users"."id" = 1054  

How can I make rails to unscope association in a join?

How do you configure ransack to strip leading and trailing whitespace as a default?

Posted: 01 Dec 2016 04:38 AM PST

I have multiple search bars (over 20) in a web application that uses a ruby's ransack gem (https://github.com/activerecord-hackery/ransack).

Does anyone know of a how I can strip out the leading and trailing white spaces for all (20+) searches?

My current solution is to create the following method in the application helper:

def strip_query    params[:q] = Hash[params[:q].map { |key, str| [key, str.strip] }] unless params[:q].blank?  end  

And call the method at the start of each controller:

 include ApplicationHelper   before_action :strip_query, only: :index  

I am looking for a DRY method that does not repeat the code in all 20+ controllers.

https://github.com/activerecord-hackery/ransack/issues/332

Suggests it possible to create a new predicate in a config/initializers/ransack.rb file, but this would require altering the searches in each view to refer to the new predicate.

What is the best way of customizing this for my problem? Is it possible to configure ransack to strip white-spaces as a default for all search queries?

How to add polymorphic address to devise custom registration controller?

Posted: 01 Dec 2016 04:07 AM PST

I'm trying to setup a custom registration controller using Devise and a polymorphic address model, but can't seem to actually get the address to save to the database.

Here is my controller:

class RegistrationsController < Devise::RegistrationsController    before_action :configure_permitted_parameters, if: :devise_controller?    def new      build_resource({})      resource.build_address      respond_with self.resource    end      def create      super    end      private    def configure_permitted_parameters      devise_parameter_sanitizer.permit(:sign_up) {|u|       u.permit(:first_name,:last_name,:mobile,:landline,:email,:password,:password_confirmation, :current_password, address_attributes: [:line_1,:line_2,:city,:region,:post_code,:country])       }    end  end  

my user model:

class User < ApplicationRecord    devise :database_authenticatable, :registerable,:recoverable, :rememberable, :trackable, :validatable    has_one :address, through: :addressable    accepts_nested_attributes_for :address    ... (other attributes)  

my address model:

class Address < ApplicationRecord    belongs_to :addressable, polymorphic: true  end  

relevant part of routes:

devise_for :users, :controllers => {registrations: 'registrations'}  devise_scope :user do    get '/login', to: 'devise/sessions#new'    get '/logout', to: 'devise/sessions#destroy'    get '/signup', to: 'devise/registrations#new'  end  

and finally the relevant part of the view view:

<%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>            <%= devise_error_messages! %>              <div class="field">              <%= f.label :first_name %><br/>              <%= f.text_field :first_name, autofocus: true %>            </div>              <div class="field">              <%= f.label :last_name %><br/>              <%= f.text_field :last_name, autofocus: true %>            </div>                <%= fields_for :address do |ff| %>                  <div class="field">                  <%= ff.label :line_1 %>                  <%= ff.text_field :line_1 %>                </div>                  <div class="field">                  <%= ff.label :line_2 %>                  <%= ff.text_field :line_2 %>                </div>                  <div class="field">                  <%= ff.label :city %>                  <%= ff.text_field :city%>                </div>                  <div class="field">                  <%= ff.label :region%>                  <%= ff.text_field :region%>                </div>                  <div class="field">                  <%= ff.label :post_code%>                  <%= ff.text_field :post_code %>                </div>                  <div class="field">                  <%= ff.label :country %>                  <%= ff.text_field :country%>                </div>            <% end %>                <div class="field">              <%= f.label :mobile %><br/>              <%= f.text_field :mobile, autofocus: true %>            </div>              <div class="field">              <%= f.label :landline %><br/>              <%= f.text_field :landline, autofocus: true %>            </div>                <div class="field">              <%= f.label :email %><br/>              <%= f.email_field :email, autofocus: true %>            </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", class: "btn btn-default" %>            </div>        <% end %>

Any help would be much appreciated! :)

Simplify multiple if else condition in rails model

Posted: 01 Dec 2016 04:38 AM PST

I have to create logic for setting status of day which is based on multiple conditions. I started out by creating multiple if else statement but it does not feel right. Please help with right approach.

def set_status_of_day(late_policy,early_departure_policy)          if late_policy.warning_on_late == "Half Day" && early_departure_policy.warning_on_late == "Half Day"              self.status_of_day = "Absent"          elsif late_policy.warning_on_late == "Half Day" && early_departure_policy.warning_on_late == "Present"              self.status_of_day = "Half Day"          elsif late_policy.warning_on_late == "Half Day" && early_departure_policy.warning_on_late == "Early Departure"              self.status_of_day = "Half Day"          elsif late_policy.warning_on_late == "Late" && early_departure_policy.warning_on_late == "Early Departure"              self.status_of_day = "Half Day"          elsif late_policy.warning_on_late == "Present" && early_departure_policy.warning_on_late == "Present"              self.status_of_day = "Present"          .          .          .          .          .          .          .          end               end  

Thanks

No template found after Update

Posted: 01 Dec 2016 04:01 AM PST

Its me again. After two of my questions were solved yesterday, lets try for anotherone. This time I have some problems with the update function of Ruby on Rails.

So, principally the update is doing well. It save the new data and everything is fine, expect one thing: When i click the "save" button, nothing happens on the frontend. As i said, the data is updated correctly, but in my opinion it should me redirect to the root_path since there is a redirect. May you can tell me what i'm doing wrong? I tried several things with other redirects/render, but nothing worked.

This code is part of my controller:

 def update      @resume = Resume.find(params[:id])      if @resume.update_attributes(resume_params)        flash[:success] = 'The file has been updated!'        redirect_to root_path      else        render 'edit'      end    end  

And this is the error I got in the logs:

No template found for ResumesController#update, rendering head :no_content  Completed 204 No Content in 96ms (ActiveRecord: 21.1ms)  

Thanks in advance!

No comments:

Post a Comment