Friday, April 1, 2016

Ruby on Rails Devise Timeoutable not working | Fixed issues

Ruby on Rails Devise Timeoutable not working | Fixed issues


Ruby on Rails Devise Timeoutable not working

Posted: 01 Apr 2016 07:31 AM PDT

I'm having trouble with the Timeoutable component of Devise in my Ruby on Rails application. I am using the remote_authenticatable feature of Devise, and I'm wondering if this is causing the problem. Basically, Devise will timeout after a certain period of inactivity. However, it will not automatically log the user out at this point. Instead, it waits until a call is made to the Rails server (i.e. a controller action is called, such as navigating to a new page), and THEN it redirects the user to the login page.

This is problematic for me because the page will contain sensitive data that I do not want others to unintentionally see just because the user stepped away from their computer and forgot to log out.

This Stack Overflow answer contains my code: http://stackoverflow.com/a/35464748/4714425

Correct Rails way of using another controller's actions within another controller - subform without nested attributes

Posted: 01 Apr 2016 07:19 AM PDT

I'm writing a section of an application which is "jobs to do" and jobs have notes or comments to them.

I'm never sure what the right way to use the nested resources views should be - I don't think nested_attributes_for is valid here - I may be wrong.

What I want to do is have the main #show action of the job render and at the foot, render the #index of the has_many model (which displays current comments) and then the #new of the has_many model, when I submit it sends via AJAX and adds the new comment to the bottom of the notes/comments panel.

I don't think that nested_attributes_for is right here as i'm not really submitting anything on the parent controller.

class JobsController < ApplicationController  end    class JobNotesController < ApplicationController  end    class Job < ActiveRecord::Base    has_many :job_notes  end    class JobNote < ActiveRecord::Base    belongs_to :job  end  

In my mind it makes more sense to render the JobNotesController's #new action from within the JobsController#show so that I could effectively send someone to the raw URL: /jobs/7/jobs_notes/34

And in my mind that way would be more DRY compatible.

I'm probably over-complicating it.

Access Control Allow Origin Error in Ember/Rails file upload to AWS

Posted: 01 Apr 2016 07:01 AM PDT

I'm trying to setup a file upload functionality to my Ember frontend using the Rails backend to create the correct JSON for authentication with my S3 bucket.

I sticking as far as I can with the ember-uploader documentation , especially with the section "Rails Setup" and also this: EmberJs: Upload files directly to S3 with EmberJS and the ember-uploader addon.

I created my bucket and changed the CORS configuration as follows:

<?xml version="1.0" encoding="UTF-8"?>  <CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">      <CORSRule>          <AllowedOrigin>http://localhost:4200</AllowedOrigin>          <AllowedMethod>GET</AllowedMethod>          <AllowedMethod>POST</AllowedMethod>          <AllowedMethod>PUT</AllowedMethod>          <AllowedHeader>*</AllowedHeader>      </CORSRule>  </CORSConfiguration>  

(The Ember frontend uses port 4200)

I've got no error messages from the Ember and Rails servers. But the developer console shows:

XMLHttpRequest cannot load http://s3-eu-west-1.amazonaws.com/my-bucket.   Response to preflight request doesn't pass access control check:  No 'Access-Control-Allow-Origin' header is present on the requested resource.   Origin 'http://localhost:4200' is therefore not allowed access.  

an the upload obviously doesn't occur.

My rails gallery controller:

class Api::V1::GalleryController < ApplicationController      def sign      @expires = 10.hours.from_now          render json: {                     acl: 'public-read',              awsaccesskeyid: ENV['AWS_ACCESS_KEY_ID'],        bucket: ENV['AWS_BUCKET'],         @expires = 10.hours.from_now            render json: {                     acl: 'public-read',              awsaccesskeyid: ENV['AWS_ACCESS_KEY_ID'],        bucket: ENV['AWS_BUCKET'],              expires: @expires,               region: 'eu-west-1',             key: "uploads/#{params[:name]}",        policy: policy,        signature: signature,        success_action_status: '201',           'Content-Type' => params[:type],        'Cache-Control' => 'max-age=630720000, public'      }, status: :ok                 end        def signature                      Base64.strict_encode64(            OpenSSL::HMAC.digest(              OpenSSL::Digest::Digest.new('sha1'),          #OpenSSL::Digest.new('sha1'),             ENV['AWS_SECRET_ACCESS_KEY'],             policy({ secret_access_key: ENV['AWS_SECRET_ACCESS_KEY'] })         )      )    end      def policy(options = {})           Base64.strict_encode64(            {                                  expiration: @expires,            conditions: [                      { bucket: ENV['AWS_BUCKET'] },              { acl: 'public-read' },                     { expires: @expires },                      { success_action_status: '201' },             [ 'starts-with', '$key', '' ],              [ 'starts-with', '$Content-Type', '' ],            [ 'starts-with', '$Cache-Control', '' ],            [ 'content-length-range', 0, 524288000 ]          ]        }.to_json      )    end    end  

Please note that I configured the bucket to be in central Europe since the AWS bucket was also created for the same zone (Frankfurt). Also I set up correctly my environment variables in Rails and checked if they show up in the console.

I don't know what I'm missing here since none of the tutorials I am following mentions how to attach the Access Control Allow Origin Header to the request and where.

How to make Minitest error codes return error message too?

Posted: 01 Apr 2016 07:18 AM PDT

Getting the following error message.
Expected response to be a <success>, but was <422>

I've got a number of 422 responses each with error messages to help the consumer of my api know what is wrong.
But the 422 I'm getting in Minitest doesn't provide the error message as well.
How can that be included in the error message?

script/runner:3:in `require': cannot load such file -- commands/runner (LoadError)

Posted: 01 Apr 2016 06:39 AM PDT

I'm trying to start a class method inside my Rails model with cron and systemd.

Unfortunatelly there seems to be somekind of path-problem when cron tries to activate the proper Rails method.

Below is my runner-script and the line causing the problem is the 3rd:

#!/usr/bin/env ruby  require File.dirname(__FILE__) + '/../config/boot'  require 'commands/runner'  

Complete error message after this is shown below:

Apr 01 09:00:01 myapp systemd[1]: Started Myapp ModelA method b.  Apr 01 09:00:02 myapp runner[25783]: /srv/myapp/current/script/runner:3:in `require': cannot load such file -- commands/runner (LoadError)  Apr 01 09:00:02 myapp runner[25783]: from /srv/myapp/current/script/runner:3:in `<main>'  

Or maybe it's because Rails is playing 1st of april's fool's joke on me?

Making a circle with profile pictures inside them

Posted: 01 Apr 2016 07:03 AM PDT

I have a website with profile pictures displayed in circles. Some people upload pictures without 1x1 ratios. Currently, the rails/scss mushes the picture into 1x1 raios. I am trying to remove the picture squishing. Is there some way to either crop the longer dimension or to add some gray-space to the shorter dimension using styling?

SCSS

@mixin avatar($size:40px) {    border-radius: 50%;    border-radius: $size/2;  }  %avatar-border-shadow {    border: 5px solid #fff;    box-shadow: 0 0 15px rgba(#000, 0.4);  }  .avatar {    @include avatar(40px);      @include mod('lg') {      width: 128px;      height: 128px;      @include avatar(128px);      @extend %avatar-border-shadow;    }  }  

HTML.SLIM

img.avatar--lg(src=display_medium_avatar(current_user))  

Note: I could just remove either the width or height parameter, but this would make the image display in varying shapes. I am hoping to have it always display in a circle.

Rails Concern dynamic relation

Posted: 01 Apr 2016 07:24 AM PDT

I write a gem for rails to have a tiny mongoid shopping cart.

in the models it get's implemented by including include MongoidCart::ActsAsProduct

class MyProduct     include Mongoid::Document       include MongoidCart::ActsAsProduct  end      module MongoidCart    class CartItem      include Mongoid::Document        belongs_to :mongoid_cart_cart, :class_name => 'MongoidCart::Cart'    end  end      module MongoidCart    class Cart      include Mongoid::Document        field :user_id, type: String        has_many :cart_items, :inverse_of => :cart, :class_name => 'MongoidCart::CartItem'      belongs_to :customer, :inverse_of => :carts, :class_name => MongoidCart.configuration.customer_model_name      end  end  

I have troubles to bring in the class_name of my Product-class to the CartItem-class. It should do automatically add a relation to the MongoidCart::CartItemclass. When I "hardcode" as :my_product I have, no errors.

How can I make the :the_class_to_point_to_as_symbol dynamic?

module MongoidCart    module ActsAsProduct      extend ActiveSupport::Concern        included do          #adds dynamic association to the CartItem to refer to the ActsAsProduct class        MongoidCart::CartItem.class_eval(          'belongs_to :the_class_to_point_to_as_symbol, :class_name => "Product", inverse_of: :cart_item'        )      end    end   end  

Getting unreadable values in dropdown menu of active admin Rails

Posted: 01 Apr 2016 07:16 AM PDT

I m getting unreadable values @ dropdown menu in active admin. I have an attribute which has a inclusion of specific values(around 10 values) but when I am making a new object of that class by using active admin... firstly it is showing the unreadable drop down menu enter image description here second its showing that attribute to be blank even if I m choosing some unreadable value.. enter image description here plz help

My form looks like this (taken from comment on answer):

form do |f|     f.semantic_errors *f.object.errors.keys     inputs 'Enter the student details' do       input :room_number       input :roll_number       input :name       input :hostel ,:as => :check_boxes       actions     end   end  

hostel_resident.rb (taken from comment):

validates :hostel,presence: true,            inclusion:{in:%w(a b c h pg j frc e g i),            message: "%{value} is not a valid hostel"}  

hostel_resident_controller#create (taken from comment):

def create     hostel = Hostel.find_by(hostel:resident_params[:hostel])     @resident = hostel.create_resident(resident_params) if hostel.present?        if @user.save       flash[:info] = "Resident Created"     else       flash[:info] = "Resident Creation Unsucessful"     end   end   

Sendgrid API and User Subscription Logic within a Rails 4 Application

Posted: 01 Apr 2016 06:12 AM PDT

I came across this post and it seems that I could avoid using the delayed jobs gem which would be preferred.

Basis of the application:

  • an outage notification system for a cable company
  • When an outage occurs at a property (or properties), a ticket gets created
  • There are over 2000 properties, so properties are split into 8 categories based on business type and geographic location
  • a user can subscribe to 8 potential categories
  • only certain users can create tickets.
  • when a ticket is created, updated, or closed, a user will get an email/sms notification if they are subscribed to one of the categories that the property is in.

The issue: emails are being sent when a ticket is created/updated closed, but there will eventually be 300+ subscribed users receiving emails. I currently have about 15 test users and when a ticket is modified, it seems 15 separate requests are being sent every time: this is quite slow in the browser (ie, the ticket modifier may wait 10+ seconds after the create/update/close button is clicked), but bearable. As more and more users subscribe, this slowness will not be tolerable.

Here is the ticket controller in full if you'd like to check it out: I realize it is fairly repetitive and doesn't follow DRY principles, and could certainly be refactored.

I'm confused on how to implement (from the linked SO post above)

headers["X-SMTPAPI"] = { :to => array_of_recipients }.to_json  

since the categorical logic is in the controller, but the app/mailers/user_notifier.rb is where the email methods are defined, and isn't that where headers["X-SMTPAPI"] = { :to => array_of_recipients }.to_json would have to go?

Line 219 of tickets_controller.rb is below.

def grab_all_sub_emails      @all_users = Subscription.where.not(name: '')      @sub_emails = @all_users.includes(:categories).map { |user| user.slice(:phone_number, :name).merge(categories: user.categories.map(&:name))}  end  

Any input on how I need to modify my logic/implement headers["X-SMTPAPI"] = { :to => array_of_recipients }.to_json to speed up the emailing process would be sincerely appreciated.

Error Installing gem `ruby2d` on Ubuntu 14.04

Posted: 01 Apr 2016 06:43 AM PDT

I am getting following error while try to install ruby2d gem on my Ubuntu 14.04

Building native extensions.  This could take a while...  ERROR:  Error installing ruby2d:      ERROR: Failed to build gem native extension.        /home/rishi/.rvm/rubies/ruby-2.2.1/bin/ruby -r ./siteconf20160401-21057-yotffi.rb extconf.rb  creating Makefile    make "DESTDIR=" clean    make "DESTDIR="  compiling ruby2d.c  ruby2d.c: In function 'render':  ruby2d.c:133:3: error: 'for' loop initial declarations are only allowed in C99 mode     for (int i = 0; i < num_objects; ++i) {     ^  ruby2d.c:133:3: note: use option -std=c99 or -std=gnu99 to compile your code  ruby2d.c:215:9: warning: ISO C90 forbids mixed declarations and code [-Wdeclaration-after-statement]           struct image_data *data;           ^  ruby2d.c:234:9: warning: ISO C90 forbids mixed declarations and code [-Wdeclaration-after-statement]           struct text_data *data;           ^  ruby2d.c: In function 'ruby2d_show':  ruby2d.c:253:3: warning: ISO C90 forbids mixed declarations and code [-Wdeclaration-after-statement]     char *title = RSTRING_PTR(rb_iv_get(self, "@title"));     ^  make: *** [ruby2d.o] Error 1    make failed, exit code 2    Gem files will remain installed in /home/rishi/.rvm/gems/ruby-2.2.1/gems/ruby2d-0.2.0 for inspection.  Results logged to /home/rishi/.rvm/gems/ruby-2.2.1/extensions/x86_64-linux/2.2.0/ruby2d-0.2.0/gem_make.out  

It would be great if anyone can give me some suggestions!

P.S. I had successfully installed simple2d gem in my machine by follow all the steps given over simple2d GitHub Page

Thanks in advance :)

Custom user page for rails using devise - Using Rails 4 and Ruby - 2.2

Posted: 01 Apr 2016 06:38 AM PDT

I am currently using devise for authentication which generates user.rb and controller for user, Welcome page(root page after authentication) which is main page of application where I need to show the total number of user created account in application, number of subject opted by current user and other details of current user. I am unable to route to user page when I am using the same user.rb and user_controller.rb.

routes.rb

  root "welcome_pages#home"    devise_for :users    resources :subjects    resources :books  

application.html.erb

    <%= link_to "Home",  root_path %></li>      <li><%= link_to "Books",   books_path %></li>      <li><%= link_to "Subjects", subjects_path %></li>      <li><%= link_to "Users", users_path %></li>  

What am I missing ? I am getting the following errors

No route matches [GET] "/users_path"  

Let me know if I need to provide more informations.

Thanks in advance.

How to pass `self` when invoking a method

Posted: 01 Apr 2016 06:57 AM PDT

I have a method that sends a message when it triggers something. The signature is:

Sender.send(user, message_id, source)  

The usage scenario is in the callbacks in active model. When some model is verified, we send a message through the template:

after_save if: 'verified_changed? && verified' do      Sender.send(user, :verified, self) # pass self as the template parameter  end  

We pass self. There are some solutions to make invoking simple as below:

after_save if: 'verified_changed? && verified' do      Sender.send(user, :verified) # not need to pass self, guess it when invoking  end  

Is there a method that passes self when a method is invoked?

More concrete examples are below:

#define a method, return the environment self  def guess  end    guess #=> main    class A      guess #=> A      def a          guess      end  end    A.new.a #=> #<A:0x000000026cd2f0>  

I share my send method below (In class Sender):

def send(*users, id, source = self)    desc = source.class.to_s    text = "There is a new process in your #{desc}: #{id}"    users.reject{|user| user.nil?}.each do |user|      send_message(user, tag: 'Process', text: text)      send_mail(user, subject: text, text: text)      send_sms(user, text: text)    end  end  

Have one method that will be used in Views, Controllers and Worker in rails app. What is best place to define it?

Posted: 01 Apr 2016 05:28 AM PDT

In my rails app I have a method that will be used in different Views, Controllers and in different Workers as well so what is best place to define this method such that code would not be get repeated.

How to get grouped_options_for_select to display the selected option on the field when searching?

Posted: 01 Apr 2016 04:57 AM PDT

I'm using grouped_options_for_select on my dropdown select field. However, when I select an option, it doesn't stay on the field as a selected option, (after I push the "search" button), but the field jumps to the first option on the list.

Search still works correctly, but I would like the field to show what the user was searching for.

This is what I tried:

  <% grouped_options = [['Europe',["London, UK", "Stockholm, Sweden"]], ['USA', ["San Francisco", "Mountain View"]]] %>    <%= f.select :location_cont, grouped_options_for_select(grouped_options) %>  

It works correctly if I display all the options as such:

<%= f.select :location_cont, ["", "San Francisco, USA", "Mountain View, USA", "Palo Alto, USA"] %>  

In the above case the selected option, that is searched, stays 'active' on the list after pushing the "search" button. But I would like to sort the options based on countries, that's why I prefer the first option with grouped_options_for_select.

How to change html class dynamically in a link_to helper

Posted: 01 Apr 2016 04:57 AM PDT

I have the following link_to helper:

 <div class="button_wrapper"><%= link_to "View Course", [course.grade, course], :class => "course_button" %></div>  

and I would like to be able to change the :class => "course_button" depending on which Subject the Course belongs to which I can specify when creating a new course. So basically I want the button to change color depending on which Subject it belongs to, for example Math will be blue and Chemistry will be green. The way im aiming to achieve this (which may not be the best way) is to create different styling in css for each subject, and then I would like the Subject name to be inputed dynamically in the :class, so the end result will be something like this if I choose maths:

<div class="button_wrapper"><%= link_to "View Course", [course.grade, course], :class => "Math_button" %></div>  

How can I achieve this?

rails: running js from rack

Posted: 01 Apr 2016 04:42 AM PDT

In rack I'd like to run js response that redirects to a page if the request type is js.

I got this far. The window.location.href = '/429.html' gets invoked, but I get this error: NameError - undefined local variable or method 'window' for Rack::Attack:Class

How should I invoke the js response to run?

if env["HTTP_X_REQUESTED_WITH"] && env["HTTP_X_REQUESTED_WITH"] == "XMLHttpRequest"    [429, {'Retry-After' => retry_after.to_s}, [window.location.href = '/429.html', content_type: 'application/javascript']]  else    [429, {'Retry-After' => retry_after.to_s}, [ActionView::Base.new.render(file: 'public/429.html', content_type: 'text/html')]]  end  

CanCan load_and_authorize_resource does not enforce authorization

Posted: 01 Apr 2016 04:20 AM PDT

I have multiple customers in the database and each of them can have multiple admins but I want to keep those customers separate and prevent from viewing each others information. I have added the following code to the ability model:

if admin_user.has_role? :admin    can [:read, :show, :edit, :update, :new_tester, :create_tester, :delete_tester], Customer, id: admin_user.customer_id  end  

When checking in the console, the abilities are set correctly. Unfortunately even though I have added load_and_authorize_resource in the controller, admin users are able to view pages (such as edit) for other customers. This is not an expected behaviour- could you please tell me if this is a bug?

This is how my controller looks like:

class Admin::CustomersController < Admin::AdminController    load_and_authorize_resource    skip_authorize_resource :only => :increase_click_counter      def edit    ...    end   ...  end  

Ruby Gem dependency versions

Posted: 01 Apr 2016 04:50 AM PDT

I finish my first gem. I want to publish it, but i have dependencies question.

My gem has dependency of active_record(~> 4.1);

And development_dependencies: rake, bundler, sqlite;

How can I determine minimal and maximal versions of rake, bundler, sqlite that will works with my gem?

Force Read From a delayed Secondary Replica set member

Posted: 01 Apr 2016 04:06 AM PDT

I have a ruby based application. Objective is to read from a mongo replica set member that is:

  1. secondary
  2. delayed by x seconds
  3. priority: 0
  4. Placed in a separate data center.

DETAILS: I have a production cluster running that uses mongo replica set.

Previously, It was noticed that sometimes Moped reads from other secondaries with high latency(remotely present in other data centers) and not from the secondary desired. To resolve the same problem, we have added a delay on remote secondaries.

Now I have a fresh analytics application that uses mongoid. Is there a way I could FORCE read from SPECIFIC secondary using mongoid or any other gem? Please suggest

how to use rails-autoprefixer in Sinatra app?

Posted: 01 Apr 2016 06:14 AM PDT

I can't make autoprefixer work. It is called, but no result in my css code.

There are instructions for Sinatra app here - https://github.com/ai/autoprefixer-rails

application.rb

class Application < Sinatra::Base    # Load path and gems/bundler    $LOAD_PATH << File.expand_path(File.dirname(__FILE__))    require "bundler"    Bundler.require    register Sinatra::AssetPipeline    assets = Sprockets::Environment.new    AutoprefixerRails.install(assets)        ### other  end  

I looked into gem source and found such examples:

@assets = Sprockets::Environment.new  @assets.append_path(@dir.join('app/app/assets/stylesheets'))  AutoprefixerRails.install(@assets, browsers: ['chrome 25'])  

or

@dir = Pathname(__FILE__).dirname  @css = @dir.join('app/app/assets/stylesheets/test.css').read  AutoprefixerRails.process(@css)  

Dynamically add file upload field which is not set in any rails model

Posted: 01 Apr 2016 03:57 AM PDT

I have a dynamic file upload option, where user can drag&drop multiple times to the form named "x", that file upload element name will be dynamically created for ex: assume 'y[dynamic_id][]', where this 'y' is not related to 'x'.

Am storing these custom fields values in separate model named 'z' with relation of 'x' & 'y'. So when upload am getting the error

undefined method `name' for nil:NilClass

What should i add in model file for this

validates_attachment_content_type : ''

Including CSS files in PDF using wicked_pdf helpers

Posted: 01 Apr 2016 04:19 AM PDT

I am successfully loading CSS files in my PDF file using wicked_pdf gem helpers:

<%= wicked_pdf_stylesheet_link_tag "pdf" %>  

This works great in development, however when i deploy in production the pdf CSS file is not correctly imported. Also note that the file is "pdf.scss.erb" and not just "pdf.css".

I am not sure how to fix this problem. Looking at the server logs, i do not see any missed file warnings.

Can find logs in access.log, Nginx with unicron

Posted: 01 Apr 2016 03:34 AM PDT

sudo vi /etc/nginx/sites-available/default file nginx service and unicorn server is running But i can not see any log in access.log and application us not accessible from the browser.

upstream app {  # Path to Unicorn SOCK file, as defined previously    server unix:/home/ubuntu/Chatting-App/shared/sockets/unicorn.sock fail_timeout=0;  }    server {    listen 80;    server_name localhost;      root /home/ubuntu/Chatting-App/public;      try_files $uri/index.html $uri @app;      location @app {      proxy_pass http://app;      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;      proxy_set_header Host $http_host;      proxy_redirect off;    }      error_page 500 502 503 504 /500.html;    client_max_body_size 4G;    keepalive_timeout 10;  }  

Unicron.rb (rails server is ruuning)

app_dir = File.expand_path("../..", __FILE__)  shared_dir = "#{app_dir}/shared"  working_directory app_dir  worker_processes 2  preload_app true  timeout 30  # Set up socket location  listen "#{shared_dir}/sockets/unicorn.sock", :backlog => 64  # Logging  stderr_path "#{shared_dir}/log/unicorn.stderr.log"  stdout_path "#{shared_dir}/log/unicorn.stdout.log"  # Set master PID location  pid "#{shared_dir}/pids/unicorn.pid"  

How to allow ActiveAdmin AdminUser to only edit their own password

Posted: 01 Apr 2016 03:27 AM PDT

Working with ActiveAdmin and I want to restrict AdminUser from editing other people's information. How can I go about doing this? This is as far as I've gotten.

controller do    def action_methods      if allow_to_edit?(user_row)        super      else        super - ['edit']      end    end  end  

I don't know how to properly define the allow_to_edit? method. I expect it to be something like this:

def allow_to_edit?(user)    current_user.id == user.id  end  

Rails - find or create by - for and array?

Posted: 01 Apr 2016 03:34 AM PDT

I'm trying to do a XXX.find_or_create_by(title: "test") but with an array of titles.

Now, if I do

XXX.where(title: ["title1", "title2"]).first_or_create  

it will only check for the first title

logic with a first_or_create

But I want to do it for ANY titles .. any idea?

Thanks !

mongoid pluck - not returning correct values with default values in model

Posted: 01 Apr 2016 04:00 AM PDT

I have a User model where there is a department field which has a default value of "Engineering".

This field was introduced 2 months after our website went live,and since its mongo, there was no migration.

When I try to get the object using where, correct value is returned

 User.find_by(:name => "John).department  

However, if I try to pluck values, it returns nil and not the default value.

 User.limit(2).pluck(:department)  

returns

[nil,"Finance"]  

I researched a bit and came across this blog post http://ahmadsherif.com/blog/2013/01/29/mongoid-default-fields-can-give-you-hard-time/

I think I am facing the same issue. Is there any work around for this? I chose to go with pluck because it's not memory intensive and saves time.

Using PdfStamper how i can get the pdf form_field max length value in ruby on rails

Posted: 01 Apr 2016 03:16 AM PDT

By using Rjb gem i want to read pdf

require 'rubygems' require 'rjb'

Ping::JavaVm.load

PdfReader = Rjb::import('com.lowagie.text.pdf.PdfReader')

PdfStamper = Rjb::import('com.lowagie.text.pdf.PdfStamper')

@pdf_reader = PdfReader.new(filename) #this will read a pdf

@pdf_reader.getNumberOfPages #will get no.of pages

To get all field_names from pdf this is the method written

def form_field_names

  return @form_field_names unless @form_field_names.nil?      fields = @form.getFields()    iterat = fields.keySet().iterator()      @form_field_names = []    while iterat.hasNext()      @form_field_names << iterat.next().to_string    end    @form_field_names   end  

my question is how can i get pdf form_field limit(max_length) value.

Bundle install works, code runs locally and tests pass on Travis-CI but fails it all fails on AWS

Posted: 01 Apr 2016 03:11 AM PDT

My current Rails (4.2.6) project works fine running on my local machine either with RAILS_ENV=test, or development, or staging, but when I try to deploy it to the staging server, hosted on AWS, it fails saying

[stderr]/usr/local/rvm/gems/ruby-2.2.4@myproject/gems/bundler-1.11.2/lib/bundler/spec_set.rb:94:in `block in materialize': Could not find activesupport-4.2.6 in any of the sources (Bundler::GemNotFound)  [stderr]    from /usr/local/rvm/gems/ruby-2.2.4@myproject/gems/bundler-1.11.2/lib/bundler/spec_set.rb:87:in `map!'  [stderr]    from /usr/local/rvm/gems/ruby-2.2.4@myproject/gems/bundler-1.11.2/lib/bundler/spec_set.rb:87:in `materialize'  [stderr]    from /usr/local/rvm/gems/ruby-2.2.4@myproject/gems/bundler-1.11.2/lib/bundler/definition.rb:137:in `specs'  [stderr]    from /usr/local/rvm/gems/ruby-2.2.4@myproject/gems/bundler-1.11.2/lib/bundler/definition.rb:182:in `specs_for'  [stderr]    from /usr/local/rvm/gems/ruby-2.2.4@myproject/gems/bundler-1.11.2/lib/bundler/definition.rb:171:in `requested_specs'  [stderr]    from /usr/local/rvm/gems/ruby-2.2.4@myproject/gems/bundler-1.11.2/lib/bundler/environment.rb:18:in `requested_specs'  [stderr]    from /usr/local/rvm/gems/ruby-2.2.4@myproject/gems/bundler-1.11.2/lib/bundler/runtime.rb:13:in `setup'  [stderr]    from /usr/local/rvm/gems/ruby-2.2.4@myproject/gems/bundler-1.11.2/lib/bundler.rb:92:in `setup'  [stderr]    from /usr/local/rvm/gems/ruby-2.2.4@myproject/gems/bundler-1.11.2/lib/bundler/setup.rb:18:in `<top (required)>'  [stderr]    from /usr/local/rvm/rubies/ruby-2.2.4/lib/ruby/site_ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require'  [stderr]    from /usr/local/rvm/rubies/ruby-2.2.4/lib/ruby/site_ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require'  

There is no question that activesupport-4.2.6 exists. bundle install works.

The command used to run the app on AWS is:

bundle exec bin/rails server --binding 0.0.0.0 -d  

(RAILS_ENV=staging on the staging server)

Running the app locally with RAILS_ENV=staging like:

RAILS_ENV=staging bundle exec bin/rails server --binding 0.0.0.0  

it runs with no issues.

Any clues welcomed.

How to get token from devise_token_auth gem in params rather than header of request?

Posted: 01 Apr 2016 03:04 AM PDT

I am using devise_token_auth gem for creating an API. This gem after sign_in sends token, uid etc through header. Also on each request to api the authenticate user is checked by checking token in header.

How can I authenticate_user by sending token and uid by url params instead of request header?

How to Use joins to extract data from multiple table in rails 2

Posted: 01 Apr 2016 02:57 AM PDT

 ReportBuilder.find_all_by_id(AssignTemplate.find_all_by_batch_id(Batch.all.map{|b| b.id}).map {|a| a.report_builder_id}.uniq)  

Now i am extracting report builder data from the above code. But I need to learn how to use joins in rails 2.

Please help me out.

Thank You

1 comment:

  1. Excellent article. Very interesting to read. I really love to read such a nice article. Thanks! keep rocking. Ruby on Rails Online Training Hyderabad

    ReplyDelete