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.