Rails: Kick a logged in user(devise) out of his session: solved

Have you ever thought of kicking a specific logged in user out of their session (for some weird reason).

If you are using devise for authentication then the short answer is no/yes. Read through the rest of the the post for explanation or scroll to the last for a hacky way.

I tried many ways to hack around to fool devise into thinking that the user session is expired but no luck. The user session cannot be accessed by other users (like from the rails console or database level).

The closest i thought I came is to trick the Timeoutable  hook. But it depends on last_request_at which is taken from the user session.  I tried messing with db fields like

current_sign_in_at, last_sign_in_at but realized that devise does not look at these fields once the user logs in.

Over all, the conclusion is that we can’t mess around with Devise which does its job well.

Note: You can still clear all the sessions for all the users using the following ways, depending on where you stored the session :

  1. Cookie Store (default) :

    Fleet::Application.config.session_store :cookie_store, key: _change_me_session.

    When you change the key the old sessions expire.

  2. Redis as session store: redis-cli flushall or delete sessions using a wildcard if we know part of the key $redis.del $redis.keys('session*').
  3. Database: If the sessions are stored in the database rake db:sessions:clear.

Update: Hacky way: After all this efforts I found out that we don’t even need to break our head to crack devise. Just change the `password` of the `user` from rails console and that will log him out.  I called it a hacky way as the user can not login again with previous password (can revert it back to normal after logout though).


Rails: can not be used with :count => 1. key ‘one’ is missing.

If you ever encountered this error probably you are trying to add/access a I18n key for a `enum` attribute. For example if my model has a `enum` value like below.

class Shipment < ApplicationRecord
   enum delivery_option: {"arrival_notice":"arrival_notice", "arrival_schedule": "arrival_schedule"}

If we want to internationalize the `values` as

Call/notify before delivery and Delivery appointment required

. In your en.yml you need to specify as below.

          one: 'Delivery Option'
          arrival_notice: "Call/notify before delivery"
          arrival_schedule: "Delivery appointment required"

I18n expects the name of-the field as the first key/value.If you forget that then you see this error. Happy coding!

When to define default constructor in java

In Object Oriented Programming calling constructor is the first step of initialization an object. There are 2 types of constructors – default and parameterized.

Default – Constructor that take zero argument is called Default Constructor. Every class needs a default constructor. A default (no-argument) constructor is automatically created only when you do not define one yourself.

Parameterized – Constructor that take arguments are called parameterized Constructors.

They can be added as per our requirement.

When you declare a parameterized constructor you must add default constructor as java stops creating one.

How to configure postgres data base in a spring boot application

There are 2 steps involved in configuring postgres sql data base to a spring boot application assuming we already have data base setup.

  1. Add postgres sql dependency to pom.xml.


2. We need to tell Spring container to look into postgres by changing the application.properties.


So the list of possible options for ddl-auto are

  • validate: validate the schema, makes no changes to the database.
  • update: update the schema.
  • create: creates the schema, destroying previous data.
  • create-drop: drop the schema when the SessionFactory is closed explicitly, typically when the application is stopped.

I added spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true as the server is throwing following warning while startup.

java.sql.SQLFeatureNotSupportedException: Method org.postgresql.jdbc42.Jdbc42Connection.createClob() is not yet implemented.

Now restart server and you should see successful db connection logs. When the connection is successful spring container tries to validate the entities in the project to the db tables.

Happy coding!

Update and Validate a rails hstore column

Rails Update hstore column

For example if i have a hstore column like below

settings public.hstore DEFAULT '"currency"=>"USD"'::public.hstore NOT NULL,

Now I will update the column to add preferences in a migration as below

class AddPreferencesToUser < ActiveRecord::Migration[5.1]
  def change
    reversible do |dir|
      dir.up do
        update <<-SQL
          UPDATE users SET settings = settings || hstore('preferences', '');


Assume we want to validate preferences to be one of  facebook, twitter, linkedin these.

the validation looks this. as enum doesn’t work with hstore key well.

store_accessor :preferences validates :preferences, inclusion: ['facebook', 'twitter', 'linkedin'], allow_blank: true

see you next time!

Java vs Ruby

Runtime differences:

In Java the program always starts with a main method. Ruby program by default creates a main Object which is an instance of class class and then starts execution on it(weird!). It always starts reading from the first line of the file, there is no specific starting point.

So when you create a ruby test file HelloWorld.rb with below statement

puts "HelloWorld"

execute it in terminal with ruby HellowWorld.rb . Ruby interpreter creates main object and then starts to execute puts.(puts is an instance method from kernel module. These methods are called without a receiver).

To test this go to terminal irb and do the following.

ruby main object

Execution differences:

Java is a compiled language so the execution is a 2 step process. compile + run.

Ruby is an interpreting language.

Both Java compiler and Ruby interpreter are written in C.

Programatic differences:

Ruby is completely object oriented what does that mean from a java perspective ?

– In java we have primitive data types such as int, float etc along with Classes and Objects. In Ruby Integer, Float etc are also Classes inherited from Numeric class which intern inherited from Object class. here is a detailed image taken from rubylearning.com which explains this.


So when you create an Integer in ruby you are creating a object for Integer class.

One more important ruby feature to discuss is duck typing.

Java is strictly or strongly typed language where we need to declare the type of variable.

Ruby has implicit and explicit type conversions.

Lets see what implicit conversion means.

duck typing

Ruby is loosely typed language where it tries to define the type of a variable implicitly as shown above. If it can not infer it it throws an error as below.

undefined local variable or method

Explicit conversion is kind of ruby’s way to type safety. I can try to convert into my expected type. see below.

ruby convert to string

Happy coding!


Difference between string and symbol in ruby

Ruby symbol and string does the same thing except symbol is more efficient in terms of memory and time.

As explained here

Symbol is the most basic Ruby object you can create. It’s just a name and an internal ID. Symbols are useful because a given symbol name refers to the same object throughout a Ruby program. Symbols are more efficient than strings. Two strings with the same contents are two different objects, but for any given name there is only one Symbol object. This can save both time and memory.

ruby string symbol

Therefore, when do we use a string versus a symbol?

  • If the contents (the sequence of characters) of the object are important, use a string
  • If the identity of the object is important, use a symbol.

We can change them to each other like this

puts “string”.to_sym.class # Symbol

puts :symbol.to_s.class    # String

Symbols are particularly useful when creating hashes and you want to have a distinction between keys and values.

Generate word document from google sheet

Generate a document out of google sheet is one of the tasks businesses wants when maintaining their data in spread sheets. It can be from PO, Bill of Lading, Invoice or what ever. Google makes it really easy for us to do this through App scripts. All  you need to have is a bit of java script knowledge.

Google does this magic by combining google api's and javascript run on it server (not everything in java script works here).

Lets assume we have a simple google sheet as below.

Lets say we want to generate a document as below.

There are 2 ways to do this.

  • Add a App script bound to the sheet (applies only to this script).

– Pros: We dont need to leave the sheet we are working on.

Can create a menu link to trigger script easily.

Write script by taking current selected range into consideration.

Business people loves it as they dont need to modify anything in the script.

– Cons: The script is applicable only to that sheet. There are ways to make it                                       available to other sheets also.

  • Create a independent App script and send sheet_id, rows to generate document as a variables.

– Pros:  It can be used for any sheet (by supplying the sheet id and row range info).

– Cons: You should know where the App script lives,  enter the the sheets id and                    rows range. It might be painful for the business people to enter all this low level                  details.

I will explain the first approach here(my favorite).

Create a document template:

Create a order summary template like this.

order summary template

Create a App script:

On the sheet menu go to `Tools` –> `Script Editor`

script editor

Give the project a name and replace the following script in it.

function onOpen() {
var ui = SpreadsheetApp.getUi();
// Or DocumentApp or FormApp.
ui.createMenu(‘XYZ Menu’)
.addItem(‘Generate PO’, ‘createDcument’)

function createDcument() {
var activeSheet = SpreadsheetApp.getActiveSpreadsheet();
var activeRange = activeSheet.getActiveRange();
var row_data = activeRange.getDisplayValues();
var scriptProperties = PropertiesService.getScriptProperties();
var template_id = scriptProperties.getProperty(‘template_id’); // document template

/***Modify indexs if you the spread sheet columns shuffle **/
var attributes = {
bill_no: “0”,
vendor: “1” ,
date: “7” ,
description: “2” ,
length: “3” ,
width: “4”,
height: “5”,
weight: “6”
var documentId = DriveApp.getFileById(template_id).makeCopy().getId();
DriveApp.getFileById(documentId).setName(‘Purchase Order PO# ‘+ row_data[0][0]);
var body = DocumentApp.openById(documentId).getBody();

for (var prop in attributes) {
var index = attributes[prop];
var propValue = row_data[0][index];
propValue = propValue ? propValue : “”;
body.replaceText(‘##’+prop+’##’, propValue);

You can find the script here also.


I made the template_id as a script variable which can be set from File –> Project Properties so that you dont need to modify the script again.

script properties

Last thing you need to do is add Sheets API and Drive API by going into Resources –> Advanced Google services and also dont forget them to enable in Console.

advanced google services

phew! all the hard work is done sit back and refresh your sheet. You should be seeing the new menu XYZ Menu —> Generate PO

new menu from app script

Click on it (for first time it asks for permissions. grant it). Go to you template folder and you should see the generated document with the bill no included in the file name.

document generated

Hope this will save you sometime. Ping me with any concerns/ comments.