Thursday, December 15, 2016

Wkhtmltopdf - weird issue with encoding diacritics | Fixed issues

Wkhtmltopdf - weird issue with encoding diacritics | Fixed issues


Wkhtmltopdf - weird issue with encoding diacritics

Posted: 15 Dec 2016 08:00 AM PST

I downloaded official and latest version of wkhtmltopdf (0.12.4) from wkhtmltopdf.org and installed it on my Ubuntu:

wget http://download.gna.org/wkhtmltopdf/0.12/0.12.4/wkhtmltox-0.12.4_linux-generic-amd64.tar.xz  tar xf wkhtmltox-0.12.4_linux-generic-amd64.tar.xz  cp wkhtmltopdf /usr/local/bin/wkhtmltopdf  

Generating a PDF I see wrong diacritics position. It's not missing, but weird render is present. See the picture (Slovak language, using UTF-8). It's happening only in Firefox (50.1.0). Safari and Chrome are OK.

enter image description here

Locally on my Mac it is working fine with special characters, same as here in the browser:

    1. Zapojenie účastníkov
    1. Účastníci analýzy
    1. Časový harmonogram
    1. Celková úspešnosť

Version of wkhtmltopdf is not known, I get empty response when I run:

wkhtmltopdf -v  

Ruby on Rails display image not on User class

Posted: 15 Dec 2016 07:27 AM PST

I have 2 Models User and Message In User index.html.erb i able to show user avatar with carrierwave. The problem is How i call User avatar on every messages in messages index.html.erb

Getting "Missing :controller key on routes definition, please check your routes." when trying to redirect

Posted: 15 Dec 2016 07:35 AM PST

I'm using Rails 5. I have this in my config/routes.rb file so that I can redirect a user to their dashboard if they are already logged in and they visit the root URL …

get '/dashboard' => 'users#show', as: :dashboard    root :to => "/dashboard", constraints: lambda { |user| user.user_signed_in? }   

However, I'm getting an error, "Missing :controller key on routes definition, please check your routes." on the line

root :to => "/dashboard", constraints: lambda { |user| user.user_signed_in? }   

Why isn't "/dashboard" getting recognized and how can I correct the problem?

cap production deploy: ActiveRecord::ConnectionNotEstablished

Posted: 15 Dec 2016 07:14 AM PST

When i deploy application(framework Sinatra) with command cap production deploy to server, get error:

The deploy has failed with an error: Exception while executing as deploy@188.166.76.199: rake exit status: 1  rake stdout: Nothing written  rake stderr: rake aborted!  ActiveRecord::ConnectionNotEstablished: No connection pool with id primary found.  /home/deploy/sudoku/shared/bundle/ruby/2.3.0/gems/activerecord-5.0.0.1/lib/active_record/connection_adapters/abstract/connection_pool.rb:874:in `retrieve_connection'  /home/deploy/sudoku/shared/bundle/ruby/2.3.0/gems/activerecord-5.0.0.1/lib/active_record/connection_handling.rb:128:in `retrieve_connection'  /home/deploy/sudoku/shared/bundle/ruby/2.3.0/gems/activerecord-5.0.0.1/lib/active_record/connection_handling.rb:91:in `connection'  /home/deploy/sudoku/shared/bundle/ruby/2.3.0/gems/activerecord-5.0.0.1/lib/active_record/migration.rb:1099:in `initialize'  /home/deploy/sudoku/shared/bundle/ruby/2.3.0/gems/activerecord-5.0.0.1/lib/active_record/migration.rb:1005:in `new'  /home/deploy/sudoku/shared/bundle/ruby/2.3.0/gems/activerecord-5.0.0.1/lib/active_record/migration.rb:1005:in `up'  /home/deploy/sudoku/shared/bundle/ruby/2.3.0/gems/activerecord-5.0.0.1/lib/active_record/migration.rb:983:in `migrate'  /home/deploy/sudoku/shared/bundle/ruby/2.3.0/gems/activerecord-5.0.0.1/lib/active_record/tasks/database_tasks.rb:161:in `migrate'  /home/deploy/sudoku/shared/bundle/ruby/2.3.0/gems/activerecord-5.0.0.1/lib/active_record/railties/databases.rake:58:in `block (2 levels) in <top (required)>'  /home/deploy/sudoku/shared/bundle/ruby/2.3.0/gems/rake-11.3.0/exe/rake:27:in `<top (required)>'  /usr/local/bin/bundle:23:in `load'  /usr/local/bin/bundle:23:in `<main>'  Tasks: TOP => db:migrate  

Setting capistrano:

#deploy.rb     lock '3.4.0'    set :application, 'my-application'  set :repo_url, 'git@github.com:user/myproject.git'    set :deploy_to, '/home/deploy/my-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      task :migrate do        on roles(:app) do          within release_path do            with rack_env: fetch(:rack_env) do              execute :rake, "db:migrate"            end          end        end      end      after 'deploy', 'migrate'    after :publishing, 'deploy:restart'    after :finishing, 'deploy:cleanup'  end  

I indicate clearly the database settings for Productions and Development in main class sinatra application

require "sinatra"  require "pry"  require "sinatra/activerecord"  require 'sinatra/flash'  require 'sinatra/base'  require "sinatra/config_file"  require "./models/user"  require "./models/game_counter"  require "./models/stash"  require "json"  require "pony"  require 'logger'      enable :static  enable :sessions    config_file '/config/config.yml'    set :public_folder, File.dirname(__FILE__) + '/assets'    configure :development do    set :database, { adapter: "sqlite3", database: "sudoku_database.sqlite3" }  end    configure :production do    set :database, { adapter: "sqlite3", database: "db/sudoku_database.sqlite3" }  end  

If select without configure :production deploy without errors. How solve this issue?

prawn how to move content dynamically

Posted: 15 Dec 2016 07:07 AM PST

I have a rails project which uses prawn to render pdf, where there is a table printed with many cells inside it, So I have 3 columns in table If the content reaches the end of one column then it should continue in the next one.

class OrderPdfNew < Prawn::Document    def initialize      cell1 = make_cell(:content => "", size: 4.5)      ....      ....      t = make_table([[cell_1a, cell_1b, cell_1c]...)      t.draw    end  end  

So this is how i need, first column has top/bottom, second column top bottom. Start from first column bottom on touching end continue in second column top then bottom last end in first top.

can anyone tell how can this be done?

docker executable file not found in $PATH

Posted: 15 Dec 2016 07:15 AM PST

Trying to run a rails migration on a running docker compose container throws this error:

$ docker-compose run webapp rails db:migrate  

ERROR: Cannot start service webapp: invalid header field value "oci runtime error: container_linux.go:247: starting container process caused \"exec: \\"rails\\": executable file not found in $PATH\"\n"

However, I can access rails from inside the container:

$ docker-compose run webapp bash  root@3fd3a87275a1:/home/app/webapp# which rails  /usr/local/rvm/gems/ruby-2.3.1/bin/rails  

My container is already running and I can GET the page:

$ curl http://localhost -i  HTTP/1.1 200 OK  Content-Type: text/html; charset=utf-8  Transfer-Encoding: chunked  Connection: keep-alive  Status: 200 OK  Cache-Control: max-age=0, private, must-revalidate  ETag: W/"b62d4f67b7b823c017534cd9727752cd"  X-Frame-Options: SAMEORIGIN  X-XSS-Protection: 1; mode=block  X-Content-Type-Options: nosniff  X-Runtime: 0.019881  X-Request-Id: eb32ec21-3a8f-4caa-a27b-2e42f0b2bce9  Date: Thu, 15 Dec 2016 15:15:59 GMT  X-Powered-By: Phusion Passenger 5.0.29  Server: nginx/1.10.1 + Phusion Passenger 5.0.29  

How do I run rails db:migrate in my container?

Dockerfile

FROM phusion/passenger-ruby23    # Set correct environment variables.  ENV HOME /root    # Use baseimage-docker's init process.  CMD ["/sbin/my_init"]    # additional packages  RUN apt-get update    # Active nginx  RUN rm -f /etc/service/nginx/down    # Install bundle of gems  WORKDIR /tmp  ADD Gemfile /tmp/  ADD Gemfile.lock /tmp/  RUN bundle install    # Copy the nginx template for configuration and preserve environment variables  RUN rm /etc/nginx/sites-enabled/default    # Add the nginx site and config  ADD webapp.conf /etc/nginx/sites-enabled/webapp.conf    RUN mkdir /home/app/webapp  COPY . /home/app/webapp  RUN usermod -u 1000 app  RUN chown -R app:app /home/app/webapp  WORKDIR /home/app/webapp    # Clean up APT when done.  RUN apt-get clean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*  EXPOSE 80  

Docker Compose

version: '2'  services:    webapp:      build: .      container_name: myapp      working_dir: /home/app/webapp      ports:        - "80:80"      environment:        - PASSENGER_APP_ENV=development      volumes:        - .:/home/app/webapp      networks:        - back-end    db:      container_name: db      image: postgres:9.4      networks:        - back-end  networks:    back-end:      driver: bridge  

writting a better regular expression in the url image extension

Posted: 15 Dec 2016 07:30 AM PST

I am writing a regular expression for the url image extension.

I obtain url from body and judge whether there is a image extension in url.

I'd like you to judge if there is a better writing a style

def invalid_extension    urls = URI.extract(body, %w(http https))    if urls.map { |x| (x.match(/\.(jpg|jpeg|png|gif|bmp)/)) }.compact.present?    errors.add(:body, "Invalid extension")  end  

Rails: Cannot access column from a join-table in a partial

Posted: 15 Dec 2016 07:06 AM PST

I want to access a column from a join-table in a partial. When I access this column in a "normal" view (e.g. fakeposts#index) it is working, however if I want to do the same in a partial, it does not work.

Example:

I have a users and a fakeposts table. For each user I want to display the fakeposts in a specific (randomized) order - namely based on a randomized_time column -, which is saved in a join table:

randomized_posts table:

user_id | fakepost_id | randomized_time  

My Models look like this:

#user.rb  has_many :randomized_fakeposts    #fakepost.rb  has_many :randomized_fakeposts    # randomized_fakepost.rb  belongs_to :fakepost  belongs_to :user  

In my fakepost_controller.rb I want to get the fakeposts for the current_user and add the column "randomized_time" to my selection:

My fakepost_controller.rb

def index    @fakeposts = Fakepost.joins(:randomized_fakeposts).where(randomized_fakeposts: {user_id: current_user.id}).select("fakeposts.*, randomized_fakeposts.randomized_time")  end  

This is working: index.html.erb

<% @fakeposts.each do |post| %>     <%= post.randomized_time %>  <% end %>  

This is not working: index.html.erb and my partial

#index.html.erb  <% @fakeposts.each do |post| %>     <%= render :partial => "layouts/individual-post", :locals => {:post => post} %>  <% end %>    #layouts/_individual-post.html.erb  <%= post.randomized_time %>  

Error message

=> undefined method `randomized_time' for #<Fakepost:0x007f7752eeab58>  

However, something like <%= post.created_at %> is working fine in my partial so I guess the way I call my partial is correct?

Populate select box based on dropdown list

Posted: 15 Dec 2016 06:53 AM PST

I am trying to get either a dropdown or selection box(prefer the later, because of the possibility to choose multiple values at once) in a webform. In this case i already got the dropdown working, based on measures.measurement_type. The second needs to be measures.measurement, filtered by the type selected in the first dropdown. I can not seem to get this working. I tried googling, but without succes. Can anyone help me get on the right track?

using ruby 4.2 Thanks

Rendering Data ServerSide with DataTables Rails

Posted: 15 Dec 2016 06:52 AM PST

I'm trying to eliminate rails from querying through a large dataset on the client-side. I did this using DataTables for another index I had of inventory_parts however that was using ActiveRecord Associations.

For this particular use case I have a method that gets all the sales opportunities for a user, for the inventory he has in stock. It's a loop that goes through the user's parts and then checks each part against the "reverse-auction" to make sure the auction is an opportunity and if it is, stick it in this array 'sales_opportunities'

So, in my Auction model I have the method:

  def self.get_sales_opportunities(user)      parts = user.inventory_parts      parts.uniq! { |part| [part[:part_num], part[:condition]] }        sales_opportunities = []      parts.each do |part|        #stick auction in sales opportunities        #if the auction is not the user's, already contains a user bid,        #or if the auction isn't asking for the part in-question's condition        Auction.where(part_num: part.part_num, active: true).each do |auction|          user_created_auction = (auction.company == user)          user_has_placed_bids = (auction.bids & user.bids).present?          part_matches = auction.condition.include?(part.condition)          all_conditions = true if auction.condition[0].blank?            sales_opportunities << auction unless user_created_auction || user_has_placed_bids || !part_matches          sales_opportunities << auction if all_conditions && auction.company != user && !user_has_placed_bids        end      end      sales_opportunities.uniq    end  

This is obviously a process and the load time is terrible..

I believe that my problem lies in the .get_sales_opportunities() mehtod, but also when trying to load server-side using DataTables my problem lies in that it expects an ActiveRecord_Associations_CollectionProxy.

Here is a snippet of app/datatables/current_opportunities_datatable.rb

  def fetch_current_opportunities      # .order does not work with an Array      current_opportunities = Auction.get_sales_opportunities(@company).order("#{sort_column} #{sort_direction}")      current_opportunities = current_opportunities.page(page).per_page(per_page)      if params[:search].present?        current_opportunities = current_opportunities.where("part_num LIKE ?", "%#{params[:search][:value]}%")      end      current_opportunities    end     .    .    .      def sort_column      columns = %w[part_num description conditions created_at elapsed_time bids lowest_bid]      columns[params[:order]["0"][:column].to_i]    end      def sort_direction      params[:order]["0"][:dir] == "desc" ? "desc" : "asc"    end  

Rails track variable change on controller refresh

Posted: 15 Dec 2016 06:44 AM PST

I have a variable in my index method:

@industry = params[:c][:ind]  

Neither the variable, nor the params get saved into a data model.

In order to use some controller logic, I need to track if @industry changed from the last controller reload. The controller reloads based on a form change. That is the form that generates params[:c][:ind]

Any ideas?

Rails: Translation for submit button on form which posts to custom action

Posted: 15 Dec 2016 07:45 AM PST

I have a TicketController, with a custom action called postpone. I would like to have custom translations on the submit button on the rails_bootstrap_form for this action. I'd like the submit button to read 'Postpone until' rather than 'Submit'. Despite adding translations to my en.yml locale, I18n reports they are missing. Where have I gone wrong?

This is on Rails 4.2.7, with rails-i18n 4.0.9, and bootstrap_form 2.5.2.

Form:

<%= bootstrap_form_for @ticket, url: postpone_ticket_path(@ticket) do |h| %>      <%= h.datetime_select :postpone_date %>      <%= h.submit t("helpers.submit.ticket.postpone") %>  <% end %>  

en.yml

en:    helpers:      submit:        ticket:          postpone: 'Postpone until'  

Ruby on Rails - Cloudinary stale request

Posted: 15 Dec 2016 06:28 AM PST

Whilst I have a user upload to cloudinary using an attachinary gem I receive a message error that says this:

Stale request - reported time is 2016-12-15 04:14:53 +0000 which is more than 1 hour ago

I have spent days trying to fix this problem. It seems like I'm the only one getting it as I have found no issues related to this.

Has anyone experienced this and if so how do I solve such an issue.

rspec mailer test with objects passed to mail method

Posted: 15 Dec 2016 06:02 AM PST

My rails application sends emails and the mailer methods require objects to be passed in as shown in the following code for the evidence_added_email method:

class EvidenceMailer < ApplicationMailer  include Rails.application.routes.url_helpers    def evidence_added_email(evidence, current_user, root_url)    @evidence = Evidence.find(evidence)    @root_url = root_url    recipients = User.where(is_auditor: true).map {|u| u.email }    blind_copy_recipients = User.where(receive_notifications: true).map {|u| u.email }    subject = 'SGPLAN: Evidência de ' + @evidence.milestone.manager.user_name + ' adicionada'    mail(to: recipients, bcc: blind_copy_recipients, from: current_user.email, subject: subject)  end    def test_email    mail(to: 'to@example.com', from: 'from@example.com', subject: 'Test Subject')  end  

The passed in evidence parameter/object requires the creation of a number of other objects. So the test spec looks like this:

require 'rails_helper'    RSpec.describe EvidenceMailer, type: :mailer do    FactoryGirl.create(:admin_user)    Agency.current = Agency.find_by(initials: 'SECTI').id    FactoryGirl.create(:department)    FactoryGirl.create(:first_plan)    Plan.current = Plan.find_by(name: 'first').id    FactoryGirl.create(:project)    FactoryGirl.create(:milestone)    FactoryGirl.create(:evidence)      describe "evidence added email" do      let(:mail) { EvidenceMailer.evidence_added_email(Evidence.find_by(name: 'Test Evidence').id,                                                       User.find_by(email: 'admin@example.com'),                                                       '/test_root_url') }      it "renders the headers" do        expect(mail.subject).to include("SGPLAN")      end    end      describe "test email" do      let(:mail) { EvidenceMailer.test_email }      it "renders the headers" do        expect(mail.subject).to eq('Test Subject')      end    end  end  

The test email example passes but the evidence added example fails with the following error:

1) EvidenceMailer evidence added email renders the headers       Failure/Error:         let(:mail) { EvidenceMailer.evidence_added_email(Evidence.find_by(name: 'Test Evidence').id,                                                          User.find_by(email: 'admin@example.com'),                                                          '/test_root_url') }         NoMethodError:         undefined method `id' for nil:NilClass       # ./spec/mailers/evidence_notifications_spec.rb:14:in `block (3 levels) in <top (required)>'       # ./spec/mailers/evidence_notifications_spec.rb:18:in `block (3 levels) in <top (required)>'  

If I execute the spec file by stepping through it with a debugger, it appears that the describe loops are each executed twice. The first time they are executed the Evidence object and all of the other objects exist but the EvidenceMailer method is not executed. The second time the objects no longer exist but the EvidenceMailer.test_email method is executed and that test passes.

I'm relatively new to rails and testing with rspec and haven't found any examples of rspec tests where parameters need to be passed into the mailer method. We're retrofitting tests to some parts of our application and I know that the evidence_added_email functionality actually works.

Our environment is as follows:

capybara (2.7.1)  poltergeist (1.6.0)  database_cleaner (1.5.3)  factory_girl_rails (4.7.0)  rails (4.2.5)  rspec-core (3.5.4)  rspec-expectations (3.5.0)  rspec-mocks (3.5.0)  rspec-rails (3.5.2)  ruby 2.3.0p0 (2015-12-25 revision 53290) [x86_64-linux]  postgresql  

Can anyone suggest how I can get this test working?

ActiveAdmin nested resources link to actions

Posted: 15 Dec 2016 05:55 AM PST

I have table Fees on show page and few panels with nested resources

How i can add links to edit, update, destroy my nested resources?

  show do |fee|      attributes_table do        row(:code, &:code)        row(:fee_group) { |fee| fee.fee_group['name'] if fee.fee_group }        row(:ssr, &:ssr)        row(:costs) { |fee| fee.costs.map { |cost| cost['currency'] }.join(', ') if fee.costs }        row(:seat_group, &:seat_group)        row(:rules, &:seat_group)      end      panel 'Cost' do        fee.costs.each do |cost|          div class: 'list-item' do            attributes_table_for cost do              row :currency              row :price              row :price              row :tax              row :default    Here i need add links                   end              end            end          end  

Limit Ransack drop down options

Posted: 15 Dec 2016 05:48 AM PST

I am using Ransack and it is working really well on our Data model. Now the issue is, in the dropdown, it shows us all the 15 option like id, name, age, gender, type, location, SSN, company, status etc.

I only want 3 options to be shown in the drop down say name, gender and location (all being text fields). How can I do it ?

data_controller.rb

@search = Data.search(params[:q].try(:merge, m: 'or'))  @datum = @search.result(:distinct=>true).paginate(page: params[:page], per_page: 30)  

data.html.erb

    <div class="row">          <div class="col-lg-10">              <div class="form_search">                  <%= search_form_for @search, url: search_data_index_path, html: { method: :get, class: "data_search" } do |f| %>                  <%= f.condition_fields do |c| %>                  <%= render "condition_fields", f: c %>                  <% end %>                  <p><%= link_to_add_fields "Add Conditions", f, :condition %></p>                  <br>                  <div class="actions">                      <%= f.submit "Search", :class => "btn btn-primary" %>                  </div>                  <% end %>              </div>          </div>      </div>  

Thanks

What is the purpose of limited_ids_for instance method in ruby? Why and How to use?

Posted: 15 Dec 2016 05:42 AM PST

Unable to find how to use limited_ids_for instance method in ruby?

Ember Engines inside Rails Engines via ember-cli-rails

Posted: 15 Dec 2016 05:37 AM PST

We have a high modular rails5 app, which is splitted in rails engines over serveral repositories and integrated as ruby gems.

Now we want to introduce EmberJS by using ember-cli-rails. The main rails application contains the main ember application in the frontend directory while each of the rails engines contain an ember engine (via ember-engine) in a frontend directory.

How to mount the ember engines of the modules into the main ember engine?

Overriding ApplicationRecord initialize, bad idea?

Posted: 15 Dec 2016 06:35 AM PST

I am creating a foo obeject like this:

@foo = Foo.new(foo_params)  @foo.bar = Bar.where(name: "baz").first_or_create  

But there are other objects that I will need to do this as well. So, I thought of overriding the Foo initialize method to do something like this:

class Foo < ApplicationRecord    def initialize(*args, BarName)      @foo = super      @foo.bar = Bar.where(name: BarName).first_or_create    end  end  

and call it like this:

@foo = Foo.new(foo_params, "baz")  

But Foo is an ApplicationRecord and it seems that it's not recommended to override the ApplicationRecord initialize method.

So how could I do this? Any other ideas? Would this initialize overriding thing work?

Rails 5 - rendering array defined in application_helper.rb

Posted: 15 Dec 2016 05:32 AM PST

I want to use nhl_scores gem to get and display recent NHL game scores on the page. This is how I defined the method in app/helpers/application_helper.rb:

def scores      games = NHLScores::Games.new      s = []      games.recent.each do |g|          s.push("#{g.away_team} @ #{g.home_team} - #{g.away_team_score}:#{g.home_team_score}")      end      s  end  

And this is how I display this array:

<ul>      <%= scores.each do |s| %>          <li><%= s %></li>      <% end %>  </ul>  

The result is:

pic with result

Yeah, for some reason the full array gets displayed after the last closing li tag but before the closing ul tag. How do I remove it? Should I define the method that returns this array elsewhere?

Can't suspend Rails 'net/http' http request when remote IP is not avaiable

Posted: 15 Dec 2016 05:09 AM PST

I have an application that makes an http request to another server instance, like this:

    http = Net::HTTP.new(ip_address, port)      Net::HTTP::Post.new("/insert", 'Content-Type' => 'application/json')      request.body(data)      response = http.request(request)      logger.info response   

It is supposed to communicate with another AWS internal instance of mine. It is working well and when the requested IP is not avaiable IT DOES timeout, like expected.

The problem is when I'm running this code on my local machine. My computer can't access this IP address, so I expected it to timeout or even raise an exception, but instead of this the program blocks completely trying to do the request and I can't even stop the server (the only way was by killing the process)!

How can I threat this case?

How do I test a Rails action with frozen strings as parameters?

Posted: 15 Dec 2016 05:03 AM PST

I have an error in a Rails 4.2.7.1 controller action where I modify the incoming parameter:

params[:temperature].gsub!(',', '.')  

Until recently this worked, but it fails in development and production now:

can't modify frozen String  

I have a fix for the problem, but I have no test that uncovers the error. Both my controller test and integration test succeed with the faulty code, and I see that the parameters are not frozen in the controller even if they are frozen when posted from the test.

How can I ensure frozen parameters arrive in the controller in my test?

How use configure :production in Sinatra framework?

Posted: 15 Dec 2016 04:37 AM PST

I have following setting database:

#app.rb  set :database, { adapter: "sqlite3", database: "name_database.sqlite3" }  

when i run cap production deploy all deploy without errors.

If i add configure :production:

#app.rb  configure :production do      set :database, { adapter: "sqlite3", database: "name_database.sqlite3" }  end  

Start again cap production deploy i get error:

ActiveRecord::ConnectionNotEstablished: No connection pool with id primary found./home/deploy/my_project/shared/bundle/ruby/2.3.0/gems/activerecord-5.0.0.1/lib/active_record/connection_adapters/abstract/connection_pool.rb:874:in `retrieve_connection'  

My setting capistrano:

#deploy/production.rb  set :stage, :production    server '188.166.76.199', user: 'deploy', roles: %w{web app db}, port: 2503  

deploy.rb

lock '3.4.0'    set :application, 'my-application'  set :repo_url, 'git@github.com:user/myproject.git'    set :deploy_to, '/home/deploy/my-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      task :migrate do        on roles(:app) do          within release_path do            with rack_env: fetch(:rack_env) do              execute :rake, "db:migrate"            end          end        end      end      after 'deploy', 'migrate'    after :publishing, 'deploy:restart'    after :finishing, 'deploy:cleanup'  end  

Ruby, merge two different objects

Posted: 15 Dec 2016 05:26 AM PST

I need to merge to different object in my Ruby on Rails application. I have my Invoice object:

class Invoice < ActiveRecord::Base {                             :id => :integer,                        :user_id => :integer,                    :description => :text,                               ......                         :status => :string,                          :price => :float  }  

And my Payment object:

class Payment < ActiveRecord::Base {              :id => :integer,           :token => :string,      :invoice_id => :integer,      :created_at => :datetime,      :updated_at => :datetime,           :email => :string  }  

With 1 to many relationship between them:

class Invoice < ActiveRecord::Base    has_many :payments    class Payment < ActiveRecord::Base    belongs_to :invoice  

Now what I would like to do is to return the Invoice object and the :email and :created_at field of the payment object associated. Right now I return the two object with the zip function:

:invoices => (user.invoices.where(:hide => false).zip user.invoices.map{|x| x.payments.last}),  

but that return an array of array:

[      [{invoice},{payment}],      [{invoice},{payment}],      ...  ]  

What I want to return is something like:

[      {invoice, :email_payment, :created_at_payment},      {invoice_1, :email_payment, :created_at_payment},      ...  ]  

How can I do that?

Company has_many users (Rails and Devise)

Posted: 15 Dec 2016 06:04 AM PST

I have a problem. It turns out that I have 2 models, Users and Companies. I need every company to have its users, until then it's easy, Company:: has_many Users Througth users_company.

What I need is to get the company to invite users and when they log in to the company panel.

By the way also normal users are logged.

Is there any guide please?

Rails 5 sanitize vs strip_tags behavior

Posted: 15 Dec 2016 04:10 AM PST

I'm using Rails 5 and (using the Rails console), typed this:

helper.sanitize("<p>Hi</p>")  => "<p>Hi</p>"  

However when I type:

helper.strip_tags("<p>Hi</p>")  => "Hi"  

I took a look at the Rails source for strip_tags:

def strip_tags(html)    self.class.full_sanitizer.sanitize(html, encode_special_chars: false)  end  

which should use helper.sanitize (what I used at the beginning) in the background. Yet, this doesn't appear to be so, because I'm getting different output from both methods.

I'm pretty sure there's some Rails magic going on in the background, just I'm not sure why. I know that if I pass some random tag in sanitize:

helper.sanitize("<p>Hi</p>", tags: ['a'])  #=> "Hi"  

I get the desired result. So, does sanitize implicitly keeps some list of white-listed tags by default? This seems to be the only explanation I can come up with...

unable to insert data using custom action by belongs with has many relationship rails

Posted: 15 Dec 2016 05:58 AM PST

My relationships are:

class PrivateClass < ActiveRecord::Base    has_many :lesson_plans  end    class LessonPlan < ActiveRecord::Base     belongs_to :private_class  end  

My form is like:

<%= form_tag (add_lesson_plan_teacher_teacher_private_school_private_class_path), remote: true do %>      <div class="row">        <div class="col-sm-6">          <div class="form-group">            <%= label_tag :title, nil, :class => "control-label" %>            <%= text_field_tag "private_class[lesson_plan][title]", "", class: "form-control first_input", required: true, style: "width: 210%;" %>          </div>          <div class="form-group">            <%= label_tag :description, nil, :class => "control-label" %>            <%= text_area_tag "private_class[lesson_plan][description]", "", placeholder: "Enter Description Here", class: "form-control", rows: "3", required: true, style: "width: 210%;" %>          </div>          <div class="form-group">            <%= label_tag :notes, nil, :class => "control-label" %>            <%= text_area_tag "private_class[lesson_plan][notes]", "", placeholder: "Enter Notes Here", class: "form-control", rows: "3", required: true, style: "width: 210%;" %>          </div>          <div class="form-group">            <%= submit_tag "Create lesson plan", :class => "btn btn-info" %>          </div>        </div>      </div>  <% end %>  

My controller:

class Teacher::PrivateClassesController < ApplicationController      before_action :authenticate_user!    before_action :set_teacher    before_action :set_private_school    before_action :set_private_class      def add_lesson_plan      @lesson_plan = @private_class.lesson_plans.new(private_class_params).save    end      private      def private_class_params      params.require(:private_class).permit!    end      def set_teacher      @teacher = Teacher.friendly.find(params[:teacher_id])    end      def set_private_school      @private_school = PrivateSchool.friendly.find(params[:private_school_id])    end      def set_private_class      @private_class = PrivateClass.find(params[:id])    end  end  

routes are:

resources :private_schools do          resources :private_classes do            member do              get :lesson_plan              post :lesson_plan              post :add_lesson_plan            end          end        end  

Now the problem is that when I try to insert data in lesson plans table it says:

ActiveRecord::UnknownAttributeError (unknown attribute 'lesson_plan' for LessonPlan.):    app/controllers/teacher/private_classes_controller.rb:11:in `add_lesson_plan'  

What I need to do is enter the lesson plan fields data into lesson plan table with private_class_id If anything wrong please correct me.

UPDATE

here are the results of puts statement:

def add_lesson_plan      puts params.inspect, '++++++++++++++++++++++++'      puts @private_class.lesson_plans.new.inspect, '**************************************'      @lesson_plan = @private_class.lesson_plans.new(private_class_params).save!    end    {"utf8"=>"✓", "private_class"=>{"lesson_plans"=>{"title"=>"ggd", "description"=>"gghh", "notes"=>"gggkd"}}, "commit"=>"Create lesson plan", "controller"=>"teacher/private_classes", "action"=>"add_lesson_plan", "teacher_id"=>"carmel-cynthia", "private_school_id"=>"dr-jasmine-e-mcnair-high-school", "id"=>"1"}  ++++++++++++++++++++++++  #<LessonPlan id: nil, title: nil, description: nil, notes: nil, subject_id: nil, teacher_id: nil, created_at: nil, updated_at: nil, is_private: true, is_publish: false, user_id: nil, publish_date: nil, popularity_count: 0, is_special: false, private_class_id: 1>  **************************************  

Editing multiple images in activeadmin

Posted: 15 Dec 2016 04:04 AM PST

In activeadmin I can create a gallery with multiple photos. I do it with carrierwave. But I have a problem while editing the gallery. I can add photos to gallery, but I can't change existing photo and delete specific photo. My code is:

schema.rb:

create_table "galleries", force: :cascade do |t|      t.string   "title"      t.integer  "admin_user_id"      t.datetime "created_at",                 null: false      t.datetime "updated_at",                 null: false      t.string   "photo",         default: [],              array: true    end  

admin/gallery.rb:

ActiveAdmin.register Gallery do      permit_params :title, :admin_user_id, photo: []      form partial: 'form'      controller do      def create        @gallery = Gallery.new(permitted_params[:gallery])        @gallery.admin_user_id = current_admin_user.id        if @gallery.save          redirect_to admin_gallery_path(@gallery)        else          render 'new', notice: 'Something went wrong.'        end      end        def update        photo = params[:gallery][:photo]        title = params[:gallery][:title]        admin_user_id = params[:gallery][:admin_user_id]        @gallery = Gallery.find(params[:id])        @gallery.title = title if title.present?        @gallery.admin_user_id = admin_user_id if admin_user_id.present?        if photo.present?          @gallery.photo += photo        elsif photo.nil?          @gallery.photo = []        else          end        @gallery.save        redirect_to admin_gallery_path(@gallery)      end      end      index do      column :id      column 'Назва', :title      column 'Фото' do |gallery|        ul do          gallery.photo.each do |photo|            li do              image_tag(photo.url(:medium)) if photo.present?            end          end        end      end      column :admin_user_id      actions    end      show do      attributes_table do        row :id        row :title        row :photo do          ul do            gallery.photo.each do |photo|              li do                image_tag(photo.url(:medium)) if photo.present?              end            end          end        end        row :admin_user_id      end    end    end  

form partial:

<% if controller.action_name == 'new' %>    <%= semantic_form_for [:admin, @gallery], html: {multipart: true}, builder: ActiveAdmin::FormBuilder do |f| %>      <%= f.semantic_errors :state %>      <%= f.inputs do %>        <%= f.input :title, label: 'Title' %>        <div class="photo-inputs">          <legend class="label"><label>Photo</label></legend>          <p>            <input type="file" name="gallery[photo][]" class="gallery-photo"><br><br>          </p>        </div>         <br>        <%= link_to 'Add photo', '#', class: 'add_another_photo_btn' %>        <%= f.input :admin_user_id, as: :hidden %>      <% end %>      <%= f.actions %>    <% end %>  <% else %>    <%= semantic_form_for [:admin, @gallery], html: {multipart: true}, builder: ActiveAdmin::FormBuilder do |f| %>      <%= f.semantic_errors :state %>      <%= f.inputs 'Gallery' do %>        <%= f.input :title %>        <%= f.input :admin_user_id, as: :select, collection: AdminUser.all.collect {|admin_user| [admin_user.name, admin_user.id] } %>        <div class="photo-inputs">          <p>            <%= f.inputs 'Photo' do %>              <% f.object.photo.each do |image| %>                <%= f.input :photo, as: :file, hint: image_tag(image.url(:thumb)), input_html: { multiple: true, value: image } if image.present? %> <br>                <%= f.input :photo_cache, as: :hidden %>              <% end %>            <% end %>          </p>        </div>        <%= link_to 'Add photo', '#', class: 'add_another_photo_btn' %>      <% end %>      <%= f.actions %>    <% end %>  <% end %>  

And finally, my activeadmin.js file:

//= require active_admin/base    function removeInput() {    $('.remove-field').click(function (ee) {      ee.preventDefault();        $(this).parents('p').remove();    });  }    $(document).ready(function () {    $('.add_another_photo_btn').click(function (e) {      e.preventDefault();      $('<p><input type="file"' + 'name="gallery[photo][]' + '"' + ' ' +        'class="gallery-photo"><a href="#" class="remove-field">Delete input</a><br><br></p>').appendTo('.photo-inputs');      removeInput();    });      $('<a href="#" class="remove-existed-file">Delete file</a>').appendTo('.file.input.optional');      $('.file.input.optional input').each(function (length) {      $(this).attr("id", "input" + length);    });      $('.remove-existed-file').click(function (e) {      e.preventDefault();      $(this).parents('li').children('input').val('');      $('<p class="info-alert">A file will be removed.</p>').appendTo($(this).parent());      $(this).remove();    })    });  

In activeadmin controller's update action, I've started to implement if/else, but I think, that I'm moving in a wrong direction. Is there any good solution to this issue? Thanks in advance.

rspec doesn't get the right value of the instance var

Posted: 15 Dec 2016 05:18 AM PST

I have a controller action with some instance variables which I want to test, here is my action code:

def index      @users_list = get_response('accounts/by_tag/QuickcallAdmin')['users'].to_a      @credit_admin = !@users_list.select{|h| h['email'] == current_user.email}.blank?      @accounts_emails = Account.pluck(:email)    end  

and the spec code:

describe 'GET #index' do      login_user      let(:account) {create(:account)}        it 'responds with 200' do        get :index, :format => :html        controller.instance_variable_set(:@users_list, [{"id"=>2, "email"=>"tes1@test.com", "tenant_id"=>1,"first_name"=>"valera","last_name"=>"rotari","phone_number"=>"89439438954", "tags"=>[{"name"=>"Program", "value"=>"my_company"}, {"name"=>"ProgramAdmin", "value"=>"new_program"}, {"name"=>"ProgramAdmin", "value"=>"new_program1"}, {"name"=>"QuickcallAdmin", "value"=>"q1"}, {"name"=>"CreditAdmin", "value"=>"q1"}]}])          expect(assigns(:credit_admin)).to eql(true)        expect(assigns(:accounts_emails)).to eql(["tes1@test.com"])      end    end  

so as you can see I try to assign some hash which I usually get from the response of the api call, and after that to see if credit_admin and account_emails vars has the right value. The problem is if I pus some puts in spec after var assignation I see my value assigned, but the test fails because credit admin variable is false and is expected as true. I got the same code and put it rails console to make a test for myself, note I use the same hash, and I have the right true value. So it seems like @users_list var is not assigned right or something like this. Also @account_email is empty array, but I have account created from factory, so it should have some value in it, seems like a common problem for both of them

wicked pdf gem is not generating the pdf view exactly same as html in rails?

Posted: 15 Dec 2016 05:49 AM PST

i am generating a pdf in my rails application. but the pdf view is not looking like an html view. in pdf view the alignment and rendering is different. dont know whats happening.

in controller

  def show_pdf_invoice      respond_to do |format|        format.html        format.pdf do      render pdf: "show_pdf_invoice"   # Excluding ".pdf" extension.        end      end    end  

and in invoises/show_pdf_invoice.html.erb

    <style>      .invoice-box{      max-width:800px;      margin:auto;      padding:30px;      border:1px solid #eee;      box-shadow:0 0 10px rgba(0, 0, 0, .15);      font-size:16px;      line-height:24px;      font-family:'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif;      color:#555;      }        .invoice-box table{      width:100%;      line-height:inherit;      text-align:left;      }        .invoice-box table td{      padding:5px;      vertical-align:top;      }        .invoice-box table tr td:nth-child(2){      text-align:right;      }        .invoice-box table tr.top table td{      padding-bottom:20px;      }        .invoice-box table tr.top table td.title{      font-size:45px;      line-height:45px;      color:#333;      }        .invoice-box table tr.information table td{      padding-bottom:40px;      }        .invoice-box table tr.heading td{      background:#eee;      border-bottom:1px solid #ddd;      font-weight:bold;      }        .invoice-box table tr.details td{      padding-bottom:20px;      }        .invoice-box table tr.item td{      border-bottom:1px solid #eee;      }        .invoice-box table tr.item.last td{      border-bottom:none;      }        .invoice-box table tr.total td:nth-child(2){      border-top:2px solid #eee;      font-weight:bold;      }        @media only screen and (max-width: 600px) {      .invoice-box table tr.top table td{          width:100%;          display:block;          text-align:center;      }        .invoice-box table tr.information table td{          width:100%;          display:block;          text-align:center;      }      }      </style>        <div class="invoice-box">      <table cellpadding="0" cellspacing="0">          <tr class="top">              <td colspan="2">                  <table>                      <tr>                          <td class="title">                              <!-- <img src="http://nextstepwebs.com/images/logo.png" style="width:100%; max-width:300px;"> -->                              <%#= wicked_pdf_image_tag("https://www.nextstepwebs.com/images/logo.png") %>                              <%= image_tag("https://www.nextstepwebs.com/images/logo.png") %>                            </td>                            <td>                              Invoice #: <%= @invoise.invoice_no %><br>                              Created: <%= @invoise.updated_at.strftime("%a, %d-%b-%y") %><br>                              Due: <%= @invoise.due_date.strftime("%a, %d-%b-%y") %>                          </td>                      </tr>                  </table>              </td>          </tr>            <tr class="information">              <td colspan="2">                  <table>                      <tr>                          <td>                              <%= @invoise.company.company_name %><br>                              <%#= @invoise.company.company_name%><br>                              <%#= @invoise.company.company_name %>                          </td>                            <td>                              <br>                              <br>                            </td>                      </tr>                  </table>              </td>          </tr>    <!--             <tr class="heading">              <td>                  Payment Method              </td>                <td>                  Check #              </td>              <td>                  Payment Method              </td>                <td>                  Check #              </td>          </tr> -->    <!--             <tr class="details">              <td>                  Check              </td>                <td>                  1000              </td>          </tr> -->            <tr class="heading">              <td>                  Item              </td>                <td>                  Quantity              </td>                <td>                  Price              </td>                <td>                  Total              </td>                          </tr>      <% @invoise.invoice_details.each do |detail| %>              <tr class="item">              <td>                  <%= detail.item %>              </td>                <td>                  <%= detail.quantity %>              </td>                <td>                  <%= detail.rate %>              </td>                <td>                  <%= detail.amount %>              </td>                                        </tr>      <% end %>                        <!--             <tr class="item last">              <td>                  Domain name (1 year)              </td>                <td>                  $10.00              </td>          </tr> -->            <tr class="total">              <td></td>              <td></td>              <td></td>                <td>                 Total: <%= @invoise.total_amount %>                </td>          </tr>        </table>      </div>  

and in gemfile

 gem 'pdfkit'   gem 'wicked_pdf'   gem 'wkhtmltopdf-binary-edge', '~> 0.12.2.1'  

and i tried rendering stylesheets with wicked_pdf_tags like this

    <%= wicked_pdf_stylesheet_link_tag 'base' %>      <%= wicked_pdf_stylesheet_link_tag 'super_admin', media: 'all', "data-turbolinks-track" => true %>      <%= wicked_pdf_javascript_include_tag 'base' %>      <%= wicked_pdf_javascript_include_tag 'super_admin', "data-turbolinks-track" => true %>      <%= csrf_meta_tags %>  

iam getting the errors when i add above wicked_tags

Sprockets::Rails::Helper::AbsoluteAssetPathError at /invoises/BRUqWOeEVNSN6GCwxQqLGg%253D%253D/show_pdf_invoice.pdf  Asset names passed to helpers should not include the "/assets/" prefix. Instead of "/assets/chosen-sprite.png", use "chosen-sprite.png"  

the same code is used for both html view and pdf view. html view looks nice. but pdf thats generated with the same code as html is not rendering exactly same as html view. pdf view alignment is changed.Wicked pdf gem, does not generate exact views as html(with the exact alignment)?

No comments:

Post a Comment