Pages

Saturday, December 19, 2015

Understanding the Rails Authenticity Token

What happens

When the user views a form to create, update, or destroy a resource, the Rails app creates a random authenticity_token, stores this token in the session, and places it in a hidden field in the form. When the user submits the form, Rails looks for the authenticity_token, compares it to the one stored in the session, and if they match the request is allowed to continue.

Why it happens

Since the authenticity token is stored in the session, the client cannot know its value. This prevents people from submitting forms to a Rails app without viewing the form within that app itself. Imagine that you are using service A, you logged into the service and everything is ok. Now imagine that you went to use service B, and you saw a picture you like, and pressed on the picture to view a larger size of it. Now, if some evil code was there at service B, it might send a request to service A (which you are logged into), and ask to delete your account, by sending a request to http://serviceA.com/close_account. This is what is known as CSRF (Cross Site Request Forgery).

Wednesday, August 5, 2015

try(), try() again in Rails

In Rails, try() lets you call methods on an object without having to worry about the possibility of that object being nil and thus raising an exception.  Let’s look at some very simple code from a Rails view.

Before

Here’s a simple example of code you might replace with try(). Say you’ve got a Productmodel in your project. A Product may or may not have a known manufacturer, and some links you only want to display if a user is logged in and has administrator rights:
  <!-- products/show.html.erb (before) -->
  <h1><%= @product.name %></h1>

  <% unless @product.manufacturer.nil? %>
    <%= @product.manufacturer.name %>
  <% end %>

  <% if current_user && current_user.is_admin? %>
    <%= link_to 'Edit', edit_product_path(@product) %>
  <% end %>
 try() can help us in a couple of places here:

Monday, July 13, 2015

Ruby Inheritance, Encapsulation and Polymorphism

Inheritance
Inheritance is a relation between two classes. A child class inherits all the features of its parent class. Methods from the parent can be overridden in the child and new logic can be added.
Usually, inheritance is used to specialize a class. See the following example :
class Document
  def initialize; end

  # logic to deal with any document

  def print
    # logic to print any kind of document
  end
end
class XmlDocument < Document
  # logic to deal with any document

  def print
    # logic to print a xml document
  end
end
A class can only inherit from one class as opposed to c++ where multi-inheritance can be done (not always for the better).

Thursday, July 9, 2015

Send PDF attachments from Rails with WickedPdf and ActionMailer

In almost any web application you create, the question of generating PDF files will pop up pretty soon. 

Setup

As always, using a ruby gem in rails is pretty simple, you just add a couple of lines to the Gemfile
gem 'wicked_pdf'
#we need the new binary here, so that we can be OS independent
gem 'wkhtmltopdf-binary', github: 'pallymore/wkhtmltopdf-binary-edge', tag: 'v0.12.2'

Usage

This setup will work pretty straightforward in the controllers, because WickedPdf registers :pdf request format, and you can respond to it in the same fashion as html or js in a respond_to block. Code below is copied from the WickedPdf Readme page.

Monday, June 1, 2015

Check if ActiveRecord object is valid with params before updating to Database

To update the attributes without saving them, you can use
@obj.assign_attributes( params[:obj] )
Then to check if the object is valid, you can call
@obj.valid?
If the object is not valid, you can see the errors (only after calling .valid?) by calling
@obj.errors
If the object is valid, you can save it by calling
@obj.save
However, all of this usually isn't necessary. If the object isn't valid, then ActiveRecord won't save the object to the database, so all of the attribute changes are forgotten when you leave the controller action.
Also, since an invalid record won't be saved to the database, you can always just call Object.find() again to get the original object back.

Wednesday, March 18, 2015

Adding Layouts to Devise Views

Add following code to your Devise.rb file

# append to end of config/initializers/devise.rb
Rails.application.config.to_prepare do
  Devise::SessionsController.layout "devise"
  Devise::RegistrationsController.layout proc { |controller| user_signed_in? ? "application" : "devise" }
  Devise::ConfirmationsController.layout "devise"
  Devise::UnlocksController.layout "devise"
  Devise::PasswordsController.layout "devise"
end

Thursday, March 12, 2015

Access WEBrick from a different PC

By using the below command, One can access webrick from different PC

rails s -b IP_ADDRESS -p PORT

Wednesday, January 14, 2015

Fetch a Average Color from an Image

One can fetch a average color from an image using Rmagick with the below snippet.

img =  Magick::Image.read("http://SOME_IMAGE_URL").first
pix = img.scale(1, 1)
avg_color_hex = pix.to_color(pix.pixel_color(0,0)
It will return the Color code(The maximum color used in that image).

Wednesday, January 7, 2015

Screens in Ubuntu

Screen is a terminal multiplexer, which allows a user to access multiple separate terminal sessions inside a single terminal window or remote terminal session. Sometimes you need to run a rake task or something else which keep on producing logs and you want to keep it running even you close your terminal.

1. Install Screen

sudo apt-get install screen screen-profiles screen-profiles-extras

2. Create Screen

screen -S name_of_screen

Run your Task in this screen.

3. Detach Screen

ctlr + a then d