Rails | Apartment gem | Resets AR objects when tenant switched

I ran into a weird situation today. Active Record objects stored in vars are removed when I switched from one tenant to another on the fly. This will create a weird test-failing scenario and you never know why its happening.

def switch(name)

@customers = [1,2,3]
switch('shiva') do |name|
  puts name
  puts @customers

# Gives output
# shiva
# 1
# 2
# 3


but when I do this

@roles     = Role.all
@customers = org.branches
@list      = [1, 2]

puts 'Role count' + @roles.count.to_s
puts 'Customer count' + @customers.count.to_s
puts 'list count' + @list.count.to_s

puts '-------'
puts 'Role count' + @roles.count.to_s
puts 'Customer count' + @customers.count.to_s
puts 'list count' + @list.count.to_s

output is

Role count2
Customer count2
list count2
Role count0
Customer count0
list count2



# apartment-2.2.0/lib/apartment/adapters/abstract_adapter.rb
#   Switch to a new tenant
#   @param {String} tenant name
def switch!(tenant = nil)
  run_callbacks :switch do
    return reset if tenant.nil?

    connect_to_new(tenant).tap do

Could not install Ruby 2.3.4 in Ubuntu 17.04 using RVM

I could not install Ruby 2.3.4 which I needed because Heroku does not support latest stable release like 2.4.0.  So my Gemfile has locked the version 2.3.4. Till now I have been manually commenting out that particular line from the Gemfile and skipping the change from Git-Commits.


I found a hack

  • install ruby 2.3 from apt-get
sudo apt-get install ruby2.3 ruby2.3-dev
  • find location of the ruby installed
which ruby2.3
# => /usr/bin/ruby2.3
  • Mount the ruby to RVM
rvm mount /usr/bin/ruby2.3 -n ruby-2.3.3

rvm list                                

rvm rubies

 * ext-ruby-2.3.3 [ x86_64 ]
   ruby-1.8.7-p371 [ x86_64 ]
   ruby-1.9.3-p551 [ x86_64 ]
=> ruby-2.4.0 [ x86_64 ]

A better option

Install Ruby from archived link

rvm mount -r https://cache.ruby-lang.org/pub/ruby/2.3/ruby-2.3.3.tar.bz2

Debugging: What is binding in Ruby?

You might have thought always whenever you wrote code binding.pry in your application to debug your application.

People often say “do binding to see whats going on”. Actually you are not doing binding but prying into the binding. So, its good to say “Please pry into that binding”.

But, what is binding in the first place? Continue reading

Developer’s checklist: Production deployment

One has to be very careful for shipping new changes/features to the production server.

When feature is said to be done

Assumption: Proper development processes have been followed

  1. Smoke Test in local machine
  2. Production Database backups
    • Generate snapshots or database-dumps
    • Store the backups in safe places
    • In case of Heroku, you will be provided with backup-tools
  3. Codebase versioning in Github / Diffusion
    • Create tags with proper naming conventions followed
    • eg V 0.1.1 or V 1.0.0 pre
  4. Deployment to production
    • Deploy the changes to the server
    • Make sure you run rake db:migrate is any migration pending
  5. Do data migrations if required
    • Already existing Production data might not co-op with your new code changes
      • reasons: there might be some data-fields manipulations or
        • new cols might have been added and data need to be filled in; data to be gathered from existing fields
    • Document the migration code you wrote for data-migrations [remember I am not taking about schema migrations]
    • eg
TransactionHistory.recurring_rewards.each do |tx|
   charge = Stripe::Charge.retrieve(tx.charge_id)
   invoice = Stripe::Invoice.retrieve(charge.invoice)
   subscription_id = invoice.subscription
   metadata = tx.transaction_additional_detail.metadata
   tx.transaction_additional_detail.update metadata: metadata.deep_merge(
                                               subscription_id: subscription_id,
                                               invoice_id: invoice.id
  1. Smoke test in production

Rails : Could not find jwt-1.5.3 in any of the sources

I have been using Capistrano for a long time for this project. This time when I tried to deploy my latest changes I stumbled upon this issue. So I documented this.


(Backtrace restricted to imported tasks)
cap aborted!
SSHKit::Runner::ExecuteError: Exception while executing as user@mysite.com: bundle exit status: 7
bundle stdout: Could not find jwt-1.5.3 in any of the sources
bundle stderr: Regenerating ruby-2.2.1 wrappers........
Regenerating ruby-2.2.1 wrappers........
/usr/local/rvm/gems/ruby-2.2.1/gems/bundler-1.11.2/lib/bundler/vendor/thor/lib/thor/shell/basic.rb:356: warning: Insecure world writable dir /usr/local/rvm/gems/ruby-2.2.1/bin in PATH, mode 042777

SSHKit::Command::Failed: bundle exit status: 7
bundle stdout: Could not find jwt-1.5.3 in any of the sources
bundle stderr: Regenerating ruby-2.2.1 wrappers........
Regenerating ruby-2.2.1 wrappers........
/usr/local/rvm/gems/ruby-2.2.1/gems/bundler-1.11.2/lib/bundler/vendor/thor/lib/thor/shell/basic.rb:356: warning: Insecure world writable dir /usr/local/rvm/gems/ruby-2.2.1/bin in PATH, mode 042777

Tasks: TOP => deploy:updated => bundler:install
(See full trace by running task with --trace)
The deploy has failed with an error: Exception while executing as deployer@ bundle exit status: 7
bundle stdout: Could not find jwt-1.5.3 in any of the sources
bundle stderr: Regenerating ruby-2.2.1 wrappers........


The reason is:


jwt 1.5.3 is yanked because of some reasons. So 1.5.3 version isn’t in repository..!

How to solve

Delete your Gemfile.lock and

$ bundle install

update your remote repo and deploy again



Should “have”s and “not have”s in your CV : for college graduates

Disclaimer: These techniques work well for IT graduates. Have not been tested for other disciplines. Please comment if they work for them as well.

If you have just completed you college or about to, you are at the right place. Here are some tips that will help while preparing you CV.

Definition of CV: a brief account of a person’s education, qualifications, and previous occupations, typically sent with a job application.

It is actually your summary, so make sure your CV describes you completely. Continue reading

Rails : acting weird : why layout is rendered when format.js

I don’t know why I am getting this issue. I have set remote: true in link_to helper method in view. and the controller is supposed to look like

class ProfilesController < ApplicationController
  def index

  def profile_setting
    respond_to do |format|

I have the file views/profiles/profile_setting.js.erb. I can even pry into the .js template using binding.pry [using pry-rails gem]. It renders the template but also renders layout i.e. layouts/application.html.erbContinue reading

Ruby && Rails : FreshDesk : SSO[Single Sign On]

Here is how SSO/ Remote Authentication works:

  • A user (agent/customer) wants to remotely log into your support portal.
  • You redirect the user to a remote login page you set up.
  • The user enters his login credentials and you validate him.
  • You perform an HMAC-MD5 hash on his login details (name, secret key, email and time stamp in that order) using the secret key Freshdesk shares with you and generate a hash.
  • You send Freshdesk the encrypted value and the user’s login details this way:
  • Freshdesk performs the same HMAC-MD5 hash on his login details using the secret key and checks if the resulting hash matches the hash you sent.
  • If they match, Freshdesk knows that the user has been validated by you already and grants access to your portal.


First Generate MD5 Hash from

# Gets MD5 HASH from some unique keys to be passed to FreshDesk
# @return [String] A Digest
def gen_hash_from_params_hash
  digest = OpenSSL::Digest.new('MD5')
  OpenSSL::HMAC.hexdigest(digest, sso_secret, url_params)


# Gets URL params in GET format
# @return [String]
# Note: This method is no more supported from May 2016
def url_params
# Gets URL params in GET format
# @return [String]
def url_params
 # Gets time in UTC for FreshDesk to compare with # @return [Time] def time_in_utc Time.now.getutc.to_i.to_s end

And finally you can generate the SSO URL for your client

# Gets URL along with params required to authenticate to FreshDesk
# Its a instance method
# @return [String]
def get_redirection_url
  sso_domain + "/login/sso?name=" + username +
      "&email=" + email +
      "&timestamp=" + time_in_utc +
      "&hash=" + gen_hash_from_params_hash +
      "&redirect_to=" + redirect_url +
      "&company=" + get_company



Useful links



Heroku : Update Cedar

The legacy Cedar-10 stack has been deprecated and reached its end-of-life on November 4, 2015. Applications may continue running, however you will not be able to push to your application without upgrading to Cedar-14 first.

Due to changes in the glibc library on Cedar-14, apps may see different memory consumption behavior on that stack. See the Performance Differences section for details. Continue reading