Pages

Sunday, February 11, 2018

Ruby’s Hash Vs ActiveSupport’s HashWithIndifferentAccess


The Hash class in Ruby’s core library retrieves values by doing a standard == comparison on the keys. This means that a value stored for a Symbol key (e.g. :some_value) cannot be retrieved using the equivalent String (e.g. ‘some_value’). 
On the other hand, class HashWithIndifferentAccess is inherited from ruby "Hash" & a special behavior is added in it. HashWithIndifferentAccess treats Symbol keys and String keys as equivalent so that the following would work:

h = HashWithIndifferentAccess.new
h[:my_value] = 'foo'
h['my_value'] #=> will return "foo"

Monday, March 20, 2017

Using will_paginate with Rails API application

It is very simple to implement will_paginate with Rails API application. We just have to pass page number and per page item. Per page item can be static also.


@posts = Post.paginate :page => params[:page]
render :json => { 
   :current_page => @posts.current_page,
   :per_page => @posts.per_page,
   :total_entries => @posts.total_entries,   
   :total_pages => @posts.total_pages,
   :entries => @posts 
 }


Tuesday, January 17, 2017

Includes vs Joins in Rails: When and where?

The most important concept to understand when using includes and joins is they both have their optimal use cases. Includes uses eager loading whereas joins uses lazy loading, both of which are powerful but can easily be abused to reduce or overkill performance.
If we first take a look at the Ruby on Rails documentation, the most important point made in the description of the includes method is:
With includes, Active Record ensures that all of the specified associations are loaded using the minimum possible number of queries.
In other words, when querying a table for data with an associated table, both tables are loaded into memory which in turn reduce the amount of database queries required to retrieve any associated data. In the example below we are retrieving all companies which have an associated active Person record:

@companies = Company.includes(:persons).where(:persons => { active: true } ).all
@companies.each do |company|
     company.person.name
end

Thursday, February 18, 2016

Best way to move files between S3 buckets - Different S3 Accounts

Here is a ruby class for performing this: https://gist.github.com/4080793

$ gem install aws-sdk
$ irb -r ./bucket_sync_service.rb
> from_creds = {aws_access_key_id:"XXX",
                aws_secret_access_key:"YYY",
                bucket:"first-bucket"}
> to_creds = {aws_access_key_id:"ZZZ",
              aws_secret_access_key:"AAA",
              bucket:"first-bucket"}
> syncer = BucketSyncService.new(from_creds, to_creds)
> syncer.debug = true # log each object
> syncer.perform
This will copy complete bucket content to new bucket.

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

Wednesday, December 10, 2014

Model Concerns in Rails 4

Concerns in Model can be used to skin-nize fat models as well as DRY up your model codes. Here is an explanation with examples:


Consider a Article model, a Event model and a Comment Model. A article or A event has many comments. A comment belongs to either article or event.
Traditionally, the models may look like this:
Comment Model:
class Comment < ActiveRecord::Base
  belongs_to :commentable, polymorphic: true
end
Article Model:
class Article < ActiveRecord::Base
  has_many :comments, as: :commentable 

  def find_first_comment
    comments.first(created_at DESC)
  end

  def self.least_commented
   #return the article with least number of comments
  end
end
Event Model
class Event < ActiveRecord::Base
  has_many :comments, as: :commentable 

  def find_first_comment
    comments.first(created_at DESC)
  end

  def self.least_commented
   #returns the event with least number of comments
  end
end
As we can notice, there is a significant piece of code common to both Event and Article Model. Using concerns we can extract this common code in a separate module Commentable.

Wednesday, December 3, 2014

Adding Password Complexity Validations To Devise

Here we have a typical Devise user model. What’s new is the password complexity validation.
class User < ActiveRecord::Base
  devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable
  attr_accessible :email, :password, :password_confirmation, :remember_me,

  validate :password_complexity

  def password_complexity
    if password.present? and not password.match(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d). /)
      errors.add :password, "must include at least one lowercase letter, one uppercase letter, and one digit"
    end
  end
end

Friday, November 21, 2014

Simple, user-friendly cancel links for your Rails forms



The default Rails view generator includes back links on form-related view templates, so if users change their mind they can easily get out of the form and on to something else. However, these links are static. What do you do if you allow users to access the form from multiple views (say, an index and a show).
Here’s a simple but effective solution I came up with: Instead of passing a static URL, I pass the HTTP referrer environment variable as the location. That way users are taken back to the page from which they opened the form to begin with.
Here’s how it works. Most of the code resides in the application_helper.rb file:
  module ApplicationHelper
    include Rails.application.routes.url_helpers

    def cancel_link
      return link_to 'Cancel', request.env["HTTP_REFERER"], 
        :class => 'cancel', 
        :confirm => 'Are you sure? Any changes will be lost.'
    end
  end
You’ll need to include Rails.application.routes.url_helpers in order to access link_to from a helper method. Then you add the helper method itself, which does nothing more than return a cancel link. Mine uses an old-style :confirm message; you can spruce it up with some less obtrusive if you’d like.
If I need a cancel link in a view, I just add
  <%= cancel_link %>
The result: a flexible, reusable cancel option that’s much more user-friendly.

Wednesday, May 28, 2014

Counters for Partials

Sometimes I like to number rows using a counter when rendering lists of things:
<% @products.each_with_index do |product, i| %>
  <li class="product_<%= i %>"><%= product.name %></li>
<% end %>
They are handy for testing, among other things.
Of course, if the content of the block gets too big I’ll factor it out into a partial. The idiomatic Rails way of doing this is to factor the block contents out into a partial and then render it with the :collectionoption:
< %= render :partial => "product", :collection => @products %>
Which is very clean, except now where do we get our row counter? As it turns out, Rails provides one for us:
  <li class="product_<%= product_counter %>"><%= product.name %></li>
Note the use of product_counter. Rails takes the name of the partial and adds _counter to it when providing the built-in counter.

Thursday, May 15, 2014

Copy a file from your system to EC2 Server with port and pem file



Here is command for Copying a file from your system to EC2 Server with port and pem file:

scp -P <PORT> -i xyz.pem  /home/user/file.txt  ec2-user@host:/home/ec2-user/

Below are the all available options that you can use based on your requirements:

scp [-12346BCpqrv] [-c cipher] [-F ssh_config] [-i identity_file] [-l limit] [-o ssh_option] [-P port] [-S program] [[user@]host1:]file1 ... [[user@]host2:]file2

Monday, May 12, 2014

Irreversible Migrations in Ruby on Rails

In Rails 2 in migrations there were only 2 methods: up and down. They are called on running migrations up and down respectively with rake tasks rake db:migrate and rake db:rollback.

In Rails 2

def up
add_column :users, :active, :boolean User.update_all(active: true) end

def down remove_column :users, :active end

Rails 3 produced us great method change which allowed us to write there code which creates a table and drops the table automatically on rolling migration back. But unfortunately there was a problem – you didn’t have opportunity to say “don’t run this peace of code on down but run this only on up”. So the solution was just to use old syntax.