breaking into the unknown…

Leave a comment

fatal error: error writing to /tmp/ccAtSusl.s: No space left on device

Recently get a frustrating error on one of the server. I introduced a new gem amatch in my rails application. I do not see any issue on local, dev or UAT server instance in installing the gem through the bundler, But on QC the bundler failed with below error:

Installing amatch 0.3.0 with native extensions
Gem::Ext::BuildError: ERROR: Failed to build gem native extension.

creating Makefile

make "DESTDIR=" clean

make "DESTDIR="
compiling amatch_ext.c
amatch_ext.c:1661:1: fatal error: error writing to /tmp/ccAtSusl.s: 
No space left on device
compilation terminated.
make: *** [amatch_ext.o] Error 1

make failed, exit code 2

Since the error clearing saying that No space left on device, I checked the space on server.

$df -h
Filesystem      Size  Used Avail Use% Mounted on
/dev/xvda1       35G  6.1G   27G  19% /
none            4.0K     0  4.0K   0% /sys/fs/cgroup
udev            1.9G   12K  1.9G   1% /dev
tmpfs           375M  304K  375M   1% /run
none            5.0M     0  5.0M   0% /run/lock
none            1.9G     0  1.9G   0% /run/shm
none            100M  4.0K  100M   1% /run/user
overflow        1.0M     0  1.0M   0% /tmp

But I see there is a lot of space on the disk

Since, the error say problem while writing to tmp folder, I checked permission of temp folder, thinking may we it causing problem.

$ ls -l / | grep tmp
drwxrwxrwt 3 root root 4096 Nov 19 13:51 tmp

But it also showing all the permissions of read and write.

Then I tried to remove all the content of tmp folder thinking , may be something is there which taking all the space

$ rm -fr /tmp/*

But again got the same error.

Now googling for some time on space distribution and partitioning on linux, came to know about overflow partition .

And I got the problem, you can see that the in the df -h command output above, the tmp is mounted on overflow . This will happen if your server continuously keep writing to tmp folder, and if you have not given a separate partition to tmp .  When system deduct some partition or memory issue it automatically mount the tmp folder to overflow partition with size of 1 MB, so that things keep working. But there is no automatic reversal i,e bringing back the tmp to root partition.

Now this could be happened on our server over the time. We have consumed our disk space, system moved tmp folder to overflow, later on we free the space by deleting unused file or increasing space, thus having free space as shown above in df -h command. But tmp folder didn’t moved back from overflow partition and having size of 1 MB. Since amatch need more then 1 MB, it is failing with space issue.

So solution is simple, unmount the tmp folder and mount it again.

# umount /tmp
umount: /tmp: device is busy.
        (In some cases useful info about processes that use
         the device is found by lsof(8) or fuser(1))

You need to kill the process using tmp folder, get the list of those process, with below command:

# lsof /tmp
Passenger 6730 root   13rW  REG   0,23        0 14247683 /tmp/passenger

Kill the running process 6730 and try to unmount again.

# kill -9 6730
# umount /tmp

Mount tmp folder again and see the disk space again.

# mount -a
# df -h
Filesystem      Size  Used Avail Use% Mounted on
/dev/xvda1       35G  6.1G   27G  19% /
none            4.0K     0  4.0K   0% /sys/fs/cgroup
udev            1.9G   12K  1.9G   1% /dev
tmpfs           375M  308K  375M   1% /run
none            5.0M     0  5.0M   0% /run/lock
none            1.9G     0  1.9G   0% /run/shm
none            100M  4.0K  100M   1% /run/user

You can see that, there is no separate overflow partition for tmp folder as it now mounted on the root partition, thus it can use all the available memory in the main partition.

This time amatch didn’t reported any issue and installed successfully.


  1. Check permission of folder
  2. Check available space.Free space and see if solve your problem
  3. If on overflow partition unmount and mount it again.


Leave a comment

mixin in ruby : include prepend extend

Ruby do not support multiple inheritance directly, but implement it through Mixin . Mixin in ruby is achieved with include, prepend and extend. prepend is introduced with Ruby 2.0. Lets see, how they work and differ from each other.

Lets define few module and classes. We will experiment with them on irb or Rails console and try to understand their behaviour

module Introduction
  def introduce
    puts "Iam Arun"

module Welcome
  def greet
    puts "Hi..How are you"

module Host
  def serve_food
    puts "chiken biryani"

module SeeOff
  def bye
    puts "Byee..."

class Person
  prepend Introduction
  include Welcome
  include Host
  extend  SeeOff

class Celebrity

Copy paste above code in irb and keep experimenting as you proceed below :

1 => include and prepend add the module method as instance method, while extend add it as class method.

Calling as class method :

2.2.1 :058 > Person.introduce
NoMethodError: undefined method `introduce’ for Person:Class

2.2.1 :059 > Person.greet
NoMethodError: undefined method `greet’ for Person:Class

2.2.1 :060 > Person.bye

You can see that, only bye method of module SeeOff worked as it is extended , so added as class method

Calling as instance method

2.2.1 :061 >
Iam Arun

2.2.1 :062 >
Hi..How are you

2.2.1 :063 >
NoMethodError: undefined method `bye’ for #<Person:0x8edec04>

Here include and prepend added the module method as instance method to the class, so it worked, but bye method of SeeOff module failed as it is added as a class method so can’t be call on the instance of Person.

Now considering the above behaviour, you may think when to use mixin as class method(using extend) and when to use as instance method(using include or prepened). It depended on the feature a module is providing and how you want to reuse it in your class. Infact in a ordinary class also, you may use the below thumb rule to define a method as a instance method or a class method.

Define a method as class method if you say want to use it within different methods of a class. say prity_print can be a class method
as it can be used in any method to well format the content before retuning it.

Second scenario is that the method behaviour not depend on the instance variable, for example it is not good idea to make full_name as class method as it depend on user’s first_name and last_name which differ from user to user, But say active_users can be a class method as it do not depend on any individual user

2. Adding module method at runtime : use extend to add method only to a specific instantiated object and use include or prepend to add instance methods to all the instance .

Above, the Celebrity class do not have any method, nor it has included or extended any of the module. Now say we want to add bye method at run time to Celebrity.

2.2.1 :065 > Celebrity.bye
NoMethodError: undefined method `bye’ for Celebrity:Class

> Celebrity.extend SeeOff
=> Celebrity
2.2.1 :067 > Celebrity.bye

Now say. we have Katrina and Deepika as two celebrity.

2.2.1 :074 > katrina =
=> #<Celebrity:0xe317eb0>
2.2.1 :075 > deepika =
=> #<Celebrity:0xe3161f0>

But we want to greet katrina only

2.2.1 :076 > katrina.extend Welcome
=> #<Celebrity:0xe317eb0>

2.2.1 :077 > katrina.greet
Hi..How are you

2.2.1 :078 > deepika.greet
NoMethodError: undefined method `greet’ for #<Celebrity:0xe3161f0>

So you can see that, when extend act on katrina i,e an object already instantiated it add greet method of Welcome as instance method to it(remember it add module method as class method to person). Basically, extend can add a module method as class Method or instance method depending on who called it at the runtime. You can check that , we have extended SeeOff as the class method above, so it will not available to katrina or deepika who are basically a instance of Celebrity class.

NoMethodError: undefined method `bye’ for #<Celebrity:0xe29b964>

Now say, you want to introduce yourself to any celebrity, thus the introduce method must be available to all its instance. In this case we have to use include.

2.2.1 :116 >Celebrity.include Introduction

2.2.1 :116 > salman =
=> #<Celebrity:0xe26d848>
2.2.1 :117 > salman.introduce
Iam Arun

2.2.1 :118 >katrina.introduce
Iam Arun

Notice that, Introduction module is mixed to Celebrity class after creation of katrina object, but its introduce method also get available to it, this is because in ruby methods are accessed by reference, any object just contain its own variable and refer for any method in its class, so if some method is added later on then also it will be accessible to a object.

3 => Just like all classes are instances of Ruby’s Class, all modules in Ruby are instances of Module.Module is the superclass of Class, so this means that all classes are also modules, and can be used as such.

You can easily check it by calling ancestors method on Person class

2.2.1 :068 > Person.ancestors
=> [Introduction, Person, Host, Welcome, Object, PP::ObjectMixin, Delayed::MessageSending, ActiveSupport::Dependencies::Loadable, V8::Conversion::Object, JSON::Ext::Generator::GeneratorMethods::Object, Kernel, BasicObject]
2.2.1 :069 >

You can note down below from the above result

  1. extend do not add the module to the ancestors chain
  2. prepend add the module as child of the class in which it is called , see that Person become ancestor of Introduction
  3. include add the ancestors in the reverse order of their call. Host include in last, so it become first ancestor of Person

As you know we can override any method in ancestors class in its child class, and also use super to keep behaviour of ancestor intact and at the same time adding our own behaviour. Let rewrite our initial code to explain this.

module Introduction
  def introduce
    puts "Iam Arun"

module Welcome
  def greet
    puts "Hi..How are you"

module Host
  def serve_food
    puts "chiken biryani"

module SeeOff
  def bye
    puts "Byee..."

class Person
  prepend Introduction
  include Welcome
  include Host
  extend  SeeOff
  def serve_food
    puts "try lassi"
  def introduce
    puts "Happy to meet you"


Now you can get below result when call different methods of the Person class.

2.2.1 :110 > person =
=> #<Person:0xb4cd9d58>

2.2.1 :111 > person.serve_food
chiken biryani
try lassi

2.2.1 :112 > person.introduce
Iam Arun
Happy to meet you

And finally, let’s see an alternative way of extending a class. I do not use it myself as I believe in keeping the things simpler. But if you go through, gems and different library, you can see the use of self.included(base) .

Basically included is a callback , which get triggered whenever a module is included into another module or class. The argument base passed to it is basically the target module or class i,e that in which the module is included. Don’t get confused as initially I was. See the example below:

module Welcome
  def self.included(base)
    base.extend SeeOff
  def greet
    puts "Hi..How are you"

module SeeOff
  def bye
    puts "Byee..."

class Person
  include Welcome

Note that, In Person class, we have only included the Welcome module, but in the Welcome module we have defined included method within which we have extended the SeeOff class with the line base.extend SeeOff , since Welcome module is included in Person class, when included callback get fired, Person will be become base class for it.So base.extend SeeOff will evaluated as Person.extend SeeOff .

You can check the result in console now:

2.2.1 :037 > Person.bye

So you can see that bye method of SeeOff class get added as class method to Person class.

That’s all about mixin in ruby..🙂

Leave a comment

Rails vs React : porting view in React

React is js framework to manage dynamic user interface . If you are a Rails Developer, you have implemented it numerous time with partial refresh.

Consider a simple scenario where a User comment on a picture or video or slide. You need to show the newly added comment in the comments list without reloading the page.

With rails you do it with partial refresh of the comment list.

It works well and you will be happy till you have tried React. Few of the Problem with Rails partial refresh is as below:

  1. You need to redraw the partial DOM, every time it get refreshed
  2. You need to reinitialize all the needed js on the partial Refresh

If data to render is large, User can easily see the Flicker on page while the partial is getting refreshed.

It give bad user experience. You can easily avoid it by using React. Infact you can completely replace Rails view with React view while using Rails for other great benefit it provides for web development.

Here, I will not going to explain React in detail, but just show you the changes you need to do or adopt to migrate from Rails view to React view. I will first show you the Rails implementation of dynamic listing of comments and then tell you the changes you need to do to make it work in React. If you already know about partial refresh in Rails, you can skip it and go directly to React Implementation

Rails Implementation : Partial Refresh of Dynamic component of View

View : (wordpress not supporting ruby view tag, so I have add the view code as image)
# slide detail page(app/views/slides/show.html.erb)


This is slide show page(only relevant part is shown), rendering the partial list comments at top, followed by a input filled for writing comment and ‘Add’ button to submit the comment. At bottom we have a form with some hidden inputs.When user click on add button we populate the comment field of this form and submit it through js.

Below is the partial listing the comments
#list_comments partial(app/views/slides/_list_comments.html.erb)


A important thing in this partial is use of highlight_mentioned_user helper for displaying comment. Remember when you mention a user name in FB comment it get highlighted. Same is achieved here with the helper method, which basically highlight the name of user mentioned in the comment. Since this method can be used anywhere, I have placed it in application helper


module ApplicationHelper

 def highlight_mentioned_user(mentioner, content)
     mentioned_users = mentioner.mentionees(User)
     mentioned_users.each do |user|
     first_name = user.first_name
     linked_name = '<a href="javascript:void(0)" class="user_highlight">' + first_name + '</a>'
     content.gsub!(first_name, linked_name)


Now let us see the js code which handle submit of comment to controller

function add_comment() {
 if ($("#slide_comment").val() === '') {
   alert("Comment can't be blank");
   return false;
 else {
   var mentioned_user = $('#slide_comment').mentionsInput('getMentions');
   var mentioned_user_ids = [];
   $.each(mentioned_user, function () {
   //mix panel event for Comment Added

   //mix panel event for @mention Used in Comment
   if(mentioned_user_ids.length > 0) {

So we have add_comment() function in js, which is binded to Add button. When user click this button, it do basic validations , other needed stuff and submit the form.

On submit of form, data passed to controller action which look as below.

# app/controllers/slides_controller.rb

class SlidesController < ApplicationController
  def add_comment
   @slide = Slide.find(params[:slide_id])
   @user_who_commented = current_user
   comment = Comment.build_from(@slide,, params[:comment])
   mentioned_user_ids = params[:slide_comment_mentioned_user].split(',').reject(&:empty?)
     slide_comment_mention_notification(params[:id], @slide, comment, @user_who_commented, mentioned_user_ids)

Now once control reach the controller action, since it is ajax call i,e request is of type XHR, Rails will render add_comment.js.erb file . In this file we will refresh the partial. It look as below

# app/views/slides/add_comment.js.erb

$('#slide_comments_swap').html('<%= escape_javascript(render partial: "slides/list_comments" ,locals: {slide: @slide} ) %>');

Here we have refreshed the partial and cleared the input field , thus completing the process.


Let start with React. Use this link to configure Reactt with your Rails App .

We are going to replace rails partial refresh with React, so we do not need the partial  _list_comments.html.erb anymore. Delete the _list_comment.html.erb partial .

The slide show page now look as below :

You can see that, our view code reduced to one react component. Also it look familiar with the way we use partial in Rail , SlideComments is the name of the React Component(equivalent to _list_comments.html.erb of rails) . We have then passed the required data for the component.

One thing to note here that React accept data as Array of Hash. When you are using rails, you have a no of way to get your data in view itself, But within React component there is no rail code. For example you have passed comments collection to list_comments partial and within that you get the name of user who has commented with comment.user.full_name . But this is not possible with the data passed to React.

In Rails view we are showing each comment with the detail : commenter pic, commenter full_name, comment date and comment text. We need all these in React view also, So you can see that I have created react_slide_comments helper to which I am passing the comments collection, which then return the needed data. The Helper code look as below :

module SlidesHelper
  include ApplicationHelper
  # create needed detail to display in react's component
  def react_slide_comments(comments)
    react_comments = []
    comments.each do |comment|
      react_comments << react_slide_comment(comment)
  # get data of individual comment
  def react_slide_comment(comment)
      commenter_name: comment.user.full_name,
      commenter_img: comment.user.picture.expiring_url(60, :thumb),
      comment_date: comment.created_at.strftime('%B %d, %Y'),
      comment_text: highlight_mentioned_user(comment, comment.body)

So at this point, we have all the required data earlier used in the Rails view. In the slide Helper we have included the Application Helper at the top as it contain the method highlight_mentioned_user used for highlighting users mentioned in a comment .

NOTE : you need to create exactly the same DOM structure as you are using in Rails. The only difference is that you will not write as HTML but as React node in JS.

I suggest everyone to use Coffee Script to write the React code, as there is two many lines of code and become cumbersome if writing in pure js.

First we will create the component SlideComments . For this create the coffee file in components folder

# app/assets/javascript/components/

@SlideComments = React.createClass
  getInitialState: ->
    comments: @props.comments
    project_scoped: @props.project_scoped
    project_id: @props.project_id
    slide_id: @props.slide_id
  getDefaultProps: ->
    comments: []
  addSlideComment: (response) ->
    if response.comment_saved
      comments = React.addons.update(@state.comments, { $push: [response.comment] })
      @setState comments: comments
  render: ->
      className: 'slide_comments_swap'
        className: 'comments'
        for comment in @state.comments
          React.createElement SlideComment, key:, comment: comment
      React.createElement SlideCommentForm, project_id: @state.project_id, slide_id: @state.slide_id,  handleNewRecord: @addSlideComment    

In render part you can see that, we are creating same DOM structure as in HTML. For each comment we have created SlideComment component displaying detail of each comment.

# app/assets/javascript/components/

@SlideComment = React.createClass
  rawMarkup: ->
    { __html: @props.comment.comment_text, sanitize: true }
  render: ->
      className: 'slide_comment'
        className: 'img-circle avatar pull-left'
        width: '30'
        src: @props.comment.commenter_img
        className: 'comment-info'
          className: 'commenter_name'
          className: 'comment_date'
          className: 'comment_text'
          dangerouslySetInnerHTML: @rawMarkup()

If you see closely, we have created the same HTML structure as the deleted _slide_comments.html.erb partial.An important thing to note here that we have used dangerouslySetInnerHTML of React in place of raw of rails. Both basically render raw html.

We also have a input box with Add button to add comment in the original Rails view. It get handled in SlideCommentForm component.

# app/assets/javascript/components/

@SlideCommentForm = React.createClass
  getInitialState: ->
    comment_body: ''
  handleKeyDown: (e)->
    if e.key == 'Enter'
  handleCommentAdd: ->
    if $('#slide_comment').val() == ''
      alert 'Comment can\'t be blank'
      mentioned_user = $('#slide_comment').mentionsInput('getMentions')
      mentioned_user_ids = []
      $.each mentioned_user, ->
        mentioned_user_ids.push @uid
        method: 'post'
        url: "/projects/#{@props.project_id}/slides/#{@props.slide_id}/add_comment"
        dataType: 'JSON'
          comment: $('#slide_comment').val()
          slide_comment_mentioned_user: mentioned_user_ids.join(',')
        success: (response) =>
          #trigger event for comments count update
            channel: 'slide'
            topic: 'comment.add'
              comments_count: response.comments_count
          #mix panel event for Comment Added
          create_mix_panel_event 'comment_added'
          #mix panel event for @mention Used in Comment
          if mentioned_user_ids.length > 0
            create_mix_panel_event '@mention_used_in_comment'
          @props.handleNewRecord response
        complete: ->
  render: ->
      className: 'input-group'
        id: 'slide_comment'
        className: 'form-control'
        type: 'text'
        placeholder: 'Add a Comment'
        name: 'comment_body'
        onKeyPress: @handleKeyDown
        className: 'input-group-btn'
          id: 'add_slide_comment'
          className: 'btn btn-info'
          onClick: @handleCommentAdd

Here you can see that we have bind onClick event to handleCommentAdd method, and place all the js logic in it like giving alert if no comment is typed and finally making the ajax call to submit the comment to server.

Delete the js code in slide.js as it is ported to React .

When user add a comment it will go to controller through ajax call . The controller code now look as below, we need to add a single line to existing controller code

  def add_comment
    @slide = Slide.find(params[:slide_id])
    @user_who_commented = current_user
    comment = Comment.build_from(@slide,, params[:comment])
    mentioned_user_ids = params[:slide_comment_mentioned_user].split(',').reject(&:empty?)
      slide_comment_mention_notification(params[:id], @slide, comment, @user_who_commented, mentioned_user_ids)
      comment.create_activity key: 'project.slide_commented', owner: current_user, recipient: comment.commentable, project_id: params[:id]
    render json: {comment_saved: comment.persisted?, comment: react_slide_comment(comment)}

The bolded line is the only line we need to change in controller, as it now need to return the newly added comment which get appended to DOM by React.

Earlier when we are doing it Rails way, we are handling the DOM refresh in add_comment.js.erb file. It is not needed anymore. Delete the add_comment.js.erb file

You are done with porting your dynamic view from Rails to React.You can summarize the steps in below line

  1. Replace Rails partial with React Component
  2. Pass needed data collection as Array of Hash
  3. Move the js code(like handling click of add button ) within React
  4. Delete add_comment.js.erb file handling partial refresh in Rails

That’s all … all your css, js, model, controller etc code will not need any change.

My aim here is to just explain the amount of work needed to move from Rails to React. I will soon explain each line of React code in detail in some other Blog.


Leave a comment

Configure Rails with React

React is js Library created by Facebook to support Dynamic UI. It glue easily with Rails and can easily substitute Rails view.

I have explained porting Rails view to React view in this post .

React gem is available which make its integration with Rails a breeze. lets setup React to work with Rails .


Add below to your Gemfile

gem 'react-rails'

Run the bundler command from terminal on your project root :

$ bundle install

Initialize react with below command

Below command will provide default setup for React in your rails App

$ rails g react:install
Running via Spring preloader in process 19546
create app/assets/javascripts/components
create app/assets/javascripts/components/.gitkeep
insert app/assets/javascripts/application.js
insert app/assets/javascripts/application.js
insert app/assets/javascripts/application.js
create app/assets/javascripts/components.js

So below three line will be added to the application.js

//= require react
//= require react_ujs
//= require components

These line will be added to the bottom of your application.js file. I suggest to move the first two line toward top just below the jquery files and keep the last line i,e components towards end of the file. The reason is that, you want react js to be called before you do any DOM manipulation. Keeping components js at bottom ensure that you can call a function defined earlier by you in React component.

For Example : my app/assets/javascript/application.js look as below

//= require jquery
//= require jquery_ujs
//= require jquery-ui
//= require react
//= require react_ujs

... other js file Iam using ...

// keep react component js at bootom as
// you may need other defined function in it
//= require components
// put other js file above react components

Now configure React Add-ons in your application. The Add-ons have many helper which help you in writing React code.

If you look at component.js file it has below content :


//= require_tree ./components

So it basically call require_tree on components folder, thus any js file you create within this folder automatically get loaded.

Add below line to application.rb file

# config/application.rb

  config.react.addons = true


This enable Reacts addons which provide a number of useful helper method listed here .

With this you are ready to start with react. While working with React you need to write a lot of JS code, So I suggest to start using Coffee Script.

Even you can try it online here and use this editor to convert your existing js code to Coffee script .

Leave a comment

image cropping with paperclip

We are using paperclip for managing files and images in our project . I assume you all know how to use paperclip with its default behaviour .

Our user model managing user profile picture with paperclip look as below :

class User < ActiveRecord::Base
	has_attached_file :picture, 
                    styles: { medium: "300x300#", thumb: "80x80#" }, 
                    content_type: ['image/jpeg','image/jpg', 'image/png'],
                    default_url: "/images/:style/missing.png", 
                    whiny: false, 
                    use_timestamp: false

I have used few of the option available with has_attached_file method of paperclip . The complete list is available here .

So what it do, when ever user select his picture from UI, paperclip creates different size of it, here medium and thumb size. you can add more style as per your need.

Now we need to enhance user experience and let him to crop the picture also, which is common now a days. So know user have to go through two steps :

STEP 1 : Crop the picture

This step just allow user to select part of the picture he want to upload rather then the whole pic. You can let the user do that by providing 4 input fields crop_x, crop_y, crop_w, crop_h which is basically x cordinate, y cordinate setting the origin from where image is to cut , with the specified width and height.

But this is not user friendly. A lot of libraries are available which can serve the above purpose in better way.

I used croppic which worked well for me . I will write on its usage on some other day. Meanwhile you can try it yourself.

Our end goal in this step is to get user selected portion of image i,e crop_x, crop_y, crop_w, crop_h

STEP 3 : Make Paperclip to work on cropped part.

So, now paperclip should create different size of cropped part rather then the whole image. To make it work we first need to understand its default behaviour of paper clip and its is in this file . Below are the important lines of this file(I have taken only the line need to understood from each method)

module Paperclip
  # Handles thumbnailing images that are uploaded.
  class Thumbnail < Processor
    attr_accessor :current_geometry, :target_geometry, :format, :whiny, :convert_options,
      :source_file_options, :animated, :auto_orient
    def initialize(file, options = {}, attachment = nil)
      geometry             = options[:geometry].to_s
      @crop                = geometry[-1,1] == '#'
      @target_geometry     = options.fetch(:string_geometry_parser, Geometry).parse(geometry)
      @current_geometry    = options.fetch(:file_geometry_parser, Geometry).from_file(@file)
    def crop?
    def transformation_command
      scale, crop = @current_geometry.transformation_to(@target_geometry, crop?)
      trans = []
      trans << "-coalesce" if animated?
      trans << "-auto-orient" if auto_orient
      trans << "-resize" << %["#{scale}"] unless scale.nil? || scale.empty?
      trans << "-crop" << %["#{crop}"] << "+repage" if crop
      trans << '-layers "optimize"' if animated?

So you can see that thumbnail class is wrapped up in paperclip module and inherit from processor class . In the initialize method it set @target_geometry and @current_geometry . The main work is handle by transformation_command method . The first line  basically give back scale of the uploaded image and its cropped part . transformation_to method is defined here .

Now we will override these methods of Thumbnail class to suit our need . Read about method overriding in this post .

We are going to create our own custom processor. Lets create a paperclip_processors folder within lib folder and add custom_processor.rb file to it. It will look as below :

module Paperclip
  class CustomCropper < Thumbnail
    def initialize(file, options = {}, attachment = nil)
      if target.crop_w && target.crop_x
        @current_geometry.width  = target.crop_w
        @current_geometry.height = target.crop_h
    def target
    def transformation_command
      # call crop processing only if user inputs are there
      if target.crop_w && target.crop_x
        crop_command = [
          "#{target.crop_w}x" \
            "#{target.crop_h}+" \
            "#{target.crop_x}+" \
        crop_command + super

Our custom_cropper inherit from thumbnail class and override its initialize and transform method. In these method if user inputs for crop is not given, super is called which exhibit the behaviour of Thumbnail without any modification . This condition is put in place as sometime user sync his data from linkedin and at that time crop inputs is not available or say we have created some user in from seed.rb file which face the same issue.

Now our custom processor is defined, we just need to modify the user model to call our custom processor explicitly and so the default thumbnail processor will be not called . The user model will now look as below :

class User < ActiveRecord::Base
	has_attached_file :picture, 
                    styles: { medium: "300x300#", thumb: "80x80#" }, 
                    content_type: ['image/jpeg','image/jpg', 'image/png'],
                    default_url: "/images/:style/missing.png", 
                    whiny: false, 
                    use_timestamp: false,
                    processors: [:custom_cropper]

        attr_accessor :crop_x, :crop_y, :crop_w, :crop_h

We have defined attr_accessor for the cordinates and width height.

The controller code will look something like as below

  def upload_profile_pic
    @user.crop_x = params[:imgX1].to_i
    @user.crop_y = params[:imgY1].to_i
    @user.crop_w = params[:imgW].to_i
    @user.crop_h = params[:imgH].to_i
    @user.picture = params[:user][:picture]

That’ s all you need to make your Paperclip custom processor .


Resources :

1 Comment

jQuery Slider drag drop with Capybara

We have used jQuery Slider in one of our application, which resize the images within our library when user move it left and right. Since the no of images we can show per page, varies as user moves the slider, we have hooked a ajax call to stop event of slider which reset the per_page value in controller.

The code look as below:

JS code:

    var setupSlider = function () {

        var sl_value = $.cookie("sl_value");
        if (sl_value === undefined) {
            savedSliderValue = 0;
        } else {
            savedSliderValue = parseInt(sl_value);

        $(".size-slider .slider").slider({
            range: "min",
            value: savedSliderValue,
            min: -50,
            max: 0,
            slide: function (event, ui) {
                var fraction = (1 + ui.value / 100),
                        newWidth = originalWidth * fraction;

                $(".slide-library .slide").width(newWidth);
            stop: function (event, ui) {
                var sl_value = $(".size-slider .slider").slider("option", "value");
                $.cookie("sl_value", sl_value);
                var expansion_factor = (0 - ui.value);
                    type: "GET",
                    url: 'desktop.js',
                    data: {
                        expansion_factor: expansion_factor
                    contentType: 'script'

Controller Logic look as Below:

    #the slide_per_page will change on slide resizing. default is 12
    cookies[:slide_per_page] ||= 12
    cookies[:slide_per_page] = params[:expansion_factor].present? ? (12 + (12 * params[:expansion_factor].to_i/50)) : cookies[:slide_per_page]
    #reset page number to 1 as library resizing reinit the pagination
    page_number = params[:expansion_factor].present? ? 1 : current_page
    @library_slides =  Slide.all.paginate(:page => page_number, :per_page => cookies[:slide_per_page])


Now the test case, need to simulate the drag drop behaviour of slider.

Problem :

We are using Capybara which do give drag_to method to simulate drag and drop, but it take argument as source and target i,e you can drop one element on other element, But here there is no such distinction for the Slider as User can drag it anywhere on slider length, left or right.


Capybara internally use Selenium and it have drag_and_drop_by method which simulate drag and drop as offset i,e as X and Y coordinate . So we will extend Capybara to have our custom method.

Well we know the solution, so lets move ahead. Now the question is where to put our code, so that Capybara pick it up and is then available in our Rspec test cases.

All Rspec configuration is loaded from spec_helper.rb file whenever, you run your Rspec tests. My spec_helper.rb file look as below

require 'database_cleaner'
require 'factory_girl_rails'
require 'support/capybara'
require 'warden'
require 'devise'

RSpec.configure do |config|
  config.include Capybara::DSL
  #many more line of configuration...

So you can see that in the third line we have required ‘support/capybara’ (complete path – spec/csupport/capybara) , this file contain capybara specific configuration and initialize Capybara whenever Rspec is run. We will add our extension code at bottom of this file


module CapybaraExtension
  def drag_by(right_by, down_by)
    base.drag_by(right_by, down_by)

module CapybaraSeleniumExtension
  def drag_by(right_by, down_by)
    driver.browser.action.drag_and_drop_by(native, right_by, down_by).perform

::Capybara::Selenium::Node.send :include, CapybaraSeleniumExtension
::Capybara::Node::Element.send :include, CapybaraExtension

So now we have a drag_by method which perfom drag and drop on element with offset.Using it we can now simulate the jQuery Slider behaviour. Finally The Rspec test case look as below

  it "it should reinit the pagination on slide resizing" do
    visit slides_desktop_path(@project)
    #pagination set to 12 and we have around 33 records so including 2,3 and next there should be 3 link. 
    #Note that in pagination previous and 1 is default and so disabled when page loads
    expect(find("div.pagination")).to have_selector(".next_page", :count => 1)
    expect(find("div.pagination")).to have_selector(".previous_page", :count => 1)
    expect(find("div.pagination")).to have_selector("em", :count => 1)
    expect(find("div.pagination em.current").text).to eq("1")
    expect(find("div.pagination")).to have_selector("a", :count => 3)
    first(".ui-slider-handle").drag_by(-50, 0)
    sleep 2
    expect(find("div.pagination")).to have_selector("a", :count => 2)
    first(".ui-slider-handle").drag_by(50, 0)
    sleep 2
    expect(find("div.pagination")).to have_selector("a", :count => 3)

That’s all. Run your test and see it passing🙂

Leave a comment

simple file upload in rails

I have been doing file upload in rails using attachment_fu in initial days and then paperclip since its arrival. But have never used simple file upload i,e without using any gems. Recently I have to redesign the paperclip upload functionality of one of my application(will discuss in some other post), So thought of starting from beginning i,e how simple uploader works, what benefits paperclip or other available gem adds to it etc .

I am assuming you already have some rails 4 application running. We will add photo upload feature to it. This will be our flow.

->There will be a upload button on new photo page.
->User upload a pic using the simple uploaded.
-> On successful upload he will be redirected to show page, displaying the uploaded image.

generate the model and controller with below command on your project root from terminal

$ rails g model Photo pic:attachement
invoke active_record
create db/migrate/20150626122526_create_photos.rb
create app/models/photo.rb

If you see the generated migration file, it has below content

class CreatePhotos < ActiveRecord::Migration
  def change
    create_table :photos do |t|
      t.attachment :pic
      t.timestamps null: false

Run migration to add the photos table

$rake db:migrate

Once the migration is complete and you chek the schema.rb file, you will see below detail of the photos table.

  create_table "photos", force: :cascade do |t|
    t.string   "pic_file_name"
    t.string   "pic_content_type"
    t.integer  "pic_file_size"
    t.datetime "pic_updated_at"
    t.datetime "created_at",       null: false
    t.datetime "updated_at",       null: false

So you can see that t.attachement in the migration file get converted into below 4 fields.

t.string “pic_file_name”
t.string “pic_content_type”
t.integer “pic_file_size”
t.datetime “pic_updated_at”

They represent internal property of any attachement. When user upload any file, you need to read these values from params and need to update these fields. Let generate the controller now

$ rails g controller photos new show create.

It will generate new, show and create action in photos controller and the corresponding views.
It will also generate get routes for all these actions.

  get 'photos/new'
  get 'photos/create'
  get 'photos/show'

remove them and replace with resourceful routes.

resources :photos

write the file upload code to the photos/new.html.erb

<%= form_for @photo, :url => photos_path, :html => { :multipart => true } do |form| %>
  <%= form.file_field :pic %>
  <%=form.submit 'upload'%>
<% end %>

This simply provide a file upload field with a upload button, which submit data to create action.

The whole controller code look as below:

class PhotosController < ApplicationController
  before_action :set_photo, only: [:show]

  def show

  def new
    @photo =

  def create
    @photo =
    @photo_object = params[:photo][:pic]
    @photo.pic_file_name = @photo_object.original_filename
    @photo.pic_content_type = @photo_object.content_type
    respond_to do |format|
        file_name_filesystem = + @photo_object.original_filename
        photo_path_on_filesystem = Rails.root.join('public','uploads', file_name_filesystem),'wb') do |file| 
        format.html { redirect_to @photo, notice: 'Photo was successfully created.' }
        format.json { render :show, status: :created, location: @photo }
        format.html { render :new }
        format.json { render json: @photo.errors, status: :unprocessable_entity }

  def set_photo
    @photo = Photo.find(params[:id])

The points to notice here is the create action. If you put debugger(I use byebug) inside the create action and try to see the params, it look as below

(byebug) pp params[:photo][:pic]
“Content-Disposition: form-data; name=\”photo[pic]\”; filename=\”user1.jpeg\”\r\nContent-Type: image/jpeg\r\n”,

(byebug) pp params[:photo][:pic].content_type

(byebug) pp params[:photo][:pic].original_filename

(byebug) pp params[:photo][:pic].tempfile

(byebug) pp params[:photo][:pic].tempfile.path

So you can see that params[:photo][:pic] is an object in itself from which we can get the name of the file, its content etc.

We have first saved file_name and content_type in db, and then write the files content in public/uploads directory of our project. So that when user visit show page next time we will show him the uploaded image.

NOTE: Instead of writing the content to filesystem, you can send it to any API which handle its storage or do whatever with the data you want to do.

Now in show.html.erb we have below code to render the uploaded photo.

<% pic_path = + @photo.pic_file_name%> 
<%img src="/uploads/<%=pic_path%>" alt="" />

So from above implementation, now we can see what paperclip or other gem add to it:

-> You do not need to handle writing the uplaoded file to filesystem yourself. Gem will take care of it
-> Gem can handle storing the uploaded file on ThirdParty storage like amazone
-> They can provide further processing on image like creating tumbnail, applying affects etc.