Devise: Remember Me Checked by Default

For ‘s login form, I want to make the ‘remember-me’ checkbox to be checked by default. Yeah I know, should be pretty easy.
But as a Lazy Programmer(tm), I immediately googled that and went to the first suitable stack overflow question.

And here is the answer, just modify the remember_me part of your devise login form like this

<%= f.check_box :remember_me, (resource.remember_me ? {} : { checked: true }) %>

The ternary check is there to prevent the case that if a user make a mistake setting their credential, the check box automatically checked on form reload even though they unchecked it before.

The SO link:

Rendering Rails Template as String


This is a nice trick that is useful, for example if you need to send an html string via an api endpoint.
Instead of constructing the string manually like this:

# api controller
@title = "some title"
@html_string ="<h1>[email protected]}</h1>"

You can put the template into a template file, for example ‘html_string.erb’, and call ‘render_to_string’

# html_string.erb
<h1><%= @title %></h1>
# api controller
@html_string = render_to_string(:html_string)

This is especially useful if the html string is dynamic and complicated, as you can use partials.

Check Array Contains only Blank Strings in Ruby

This is a nice trick that I recently learned. So, this is a part of an app integration with Google Sheet. The array is an interpretation of a row. The app should check if all the values inside the row is valid, but should skip if the row is empty. Now sometimes people left some space unintentionally inside some cells. These cells technically are not empty, but I wish the app is smart enough to detect this and mark the row as empty.

For example:

my_array = ["    ", "  ", "", "       "]

I have to detect my_array as an array of blank string

So here’s the check that I use: { |e| e.gsub(/[[:space:]]/, "") }.uniq == [""]

Here’s another check that use Rails, based on some input that I got (thanks guys)

my_array is the array that you want to check. gsub will deletes all spaces inside string element of the array. then uniq equality will check if there is any non empty string left.

Ok, hopefully this trick can be useful for other people. Cheers!

Be Careful with Not

One thing that I like with ruby is it have a lot of English sounding keywords: not, and, or, unless, etc. However, you should be aware that these keyword might not be equivalent with their “traditional” counterpart.

Take `not` for example. We use `not` to negate a boolean, which we traditionally use bang (!) for. However, not has different precedence level from `!`. In ruby, `!` has the highest precedence, while not has one of the lowest precedence, like you can see in the ruby docs. This might have surprising effect.

!true && false
=> false
not true && false
=> true

In the first example, ! has higher precedence than `&&`, so it will evaluates as `(!true) && false`. However in the second example `not` has lower precedence than `&&`, so it will evaluates as `not(true && false)`.

Another example

a = true
b = not a
b = !a
=> true

Because of this subtle difference, I avoid using not and just use ! every time.


Loading Gem from Local Source

As a ruby programmer, we are treated with a rich ecosystem of library called the ruby gems.

Along the way, sometime you found a new need that can’t be fulfilled by your current gem choice. This happened to me last month with geocoder.

When this happens you have two choices:
1. Roll out your own solution from scratch
2. Patch the current gem so that it can solve your problem

From my case, I need to use Googe Places Search API for geocoding, that the geocoder didn’t support yet. I check that it is not difficult to patch the gem (not always the case) and my code base already uses the gem a lot, so I decided to patch the gem.

It might be confusing if this is the first time you want to patch a gem. How to do edit the files locally? Turns out it is quite easy.
First, fork the gem repository, and clone the fork to your local computer, for example to:


Then modify your project Gemfile to specify your local path:

# Gemfile
gem 'geocoder', path: '~/gempatch/geocoder'

Run bundle and voila! your project is running the gem from local source. Any modification you made on the gem locally will be immediately reflected on your project. Once you are happy with your modification, save and commit your change, and push it to the gem fork on your repository.

Now you can set your project to use the gem from your repository, so it will work in production

# Gemfile
gem 'geocoder', git: "git://", branch: "place-search"

Oh, and please consider to create a Pull Request to the main repository of the gem. It’s a nice way to contribute to the community and also great to put your name out there. Just make sure to read if the gem have any contributing guidelines before doing so.

Happy patching!

PS. Thanks a lot for Tyler Tringas from Storemapper for sponsoring my contribution work to the Geocoder gem.

Faster and Lighter with pluck_to_hash Gem

Rails Active Record is very convenient. It has many utilities that makes dealing with data and persistence a breeze. Without AR, I don’t think I will stick with Rails.

However, as it goes, there’s no free lunch. Active Record objects are big and heavy. Often this is an acceptable trade off. However, when you need to process a lot of record and intend to just read the attributes values, AR might be too heavy and unnecessary.

When you only need values of some fields from a record, you can use AR’s `pluck`
For example you need the name and address of a user

User.where(id: 7).pluck(:name, :location).first
# ["John Shepard", "Normandy"]

This will retrieve the requested values without instantiating AR object, which save you both time and memory.

However, if you need to retrieve a lot of values from a collection of records, processing the arrays of values can become unwieldy. An example of this case is if you are building an “index” endpoint of an api with thousands of records per request. This is a real case that I have to do in one of my project.

For this, there is a handy gem that is called “pluck_to_hash”.
No points for guessing it’s function. Basically it extends AR so you can do this:

User.limit(2).pluck_to_hash(:name, :location)
# [{:name=>"John Shepard", :location=>"Normandy"}, {:name=>"Urdnot Wrex", :location=>"Tuchanka"}]

Nice right?

Also, if you happens to use RABL for JSON templating, worry not, the gem also got you covered. RABL needs the record attributes to be accessible from a dot notation. This gem also supply `pluck_to_struct`, which looks like this

User.limit(2).pluck_to_struct(:name, :location)
# [#<struct name="John Shepard", location="Normandy"> #<struct name="Urdnot Wrex", location="Tuchanka">]

On one case, converting AR object to struct gave me ~3x faster response, while drastically reduce the memory usage. Unfortunately I don’t monitor exactly how much the memory saving from that particular endpoint, but the app server memory usage is reduced by 40%, so it should be more than that.

So, if you only need to read from some records and looking for more performance, this approach offer you some low hanging fruits.

My 2017 Goal: One Product Every Other Month

Okay, I have finally decided to do this. I am going to launch a product once every two months.

This all started when I read the post by Pieter Levels here. And I say, hmm.. not such a bad idea. But let’s not be so rad and do six instead of 12 a year.

But why? Several reasons:
1. It forces me to ship my ideas. I always getting some ideas about what would make a great product. With the constraint of shipping every other month, I have to pick some of those ideas and see if they are really as good as I thought
2. It will improve my technical capabilities, since I will build the products mostly by myself.
3. It will bring some products that hopefully can make some people life a little bit better.
4. It is going to be fun.

While I do have rough ideas of what I am going to build, they all are not finalized yet (except for the first product, which already in use by me). However they all are going to have these characteristics:
1. They are going to be small, you can’t build a facebook in two months right?
2. They will be a paid product, meaning they will get their revenue directly from their user, no “monetization” scheme
3. They will neither be designed nor executed to have neck-breaking growth

Ok, That’s it. I am going to do this. This post will be updated with every product that I launch. Want to join me?

Checking Idle Transaction on Heroku’s Postgresql

If you ever have connection problem with your postgresql instance on heroku, this post might help you.

One time one of my resque workers is dead when running long query (deleteing ~80k rows in a table). After that I got tons of timeout errors from my app. I even can’t do DELETE and UPDATE from one-off dyno

First, lets check all the process connected to your heroku postgresql instance

heroku pg:ps -a appname

you can see if there is some “idle in transaction” process. It’s likely the culprit. Take notes of the pid, then kill it with

heroku pg:kill pid_number -a appname

After you kill all those idle processes, your database should be free again.

Role models are important

There are things that I wish I knew earlier when I just started learning to code. One of them is the existence of static code analyzer / linter. Using them will teach us about many style guide that established company use and make our beginnerish code better.

I learn a lot by copying, including copying other people style. Now of course as you gained more experience and understanding you might develop some preference that deviates from other’s. But it is useful to know where the norm are.

In Ruby, the de facto one tool to do this is Rubocop. I found out about Rubocop more than one year after I start learning Ruby. When I run it againts my old codes, I see tons of “offense” hahah. I think more people should know about rubocop earlier. That’s why, I did a talk about it in id-ruby community!

Here’s the slides if you want to look.

Now that I am starting to learn Javascript seriously, I will not make the same mistake. I look around for Javascript’s Rubocop and I found eslint. Let’start coding and revising!


  • I steal the title from Rubocop, which is a quote from Robocop


Time to Start Giving Back

Recently, I realized something.

This is my github profile if viewed when I logged in:

github private

and this is if viewed when logged out

github logged out

What do they tell? They mean that my contribution to private repository totally dominates my programming life. It is even worse actually, since some of my projects were done in bitbucket.

Now, web development is my bread and butter, so of course my for-profit project will dominate. But I have benefit so much from the open source community, my career actually depend on it, that not giving back is not an option.

So, now I intend to consciously spend more effort to contribute to open source repository.  I have started some:

  1. This is my first PR ever that has been merged in to other people’s repository, only two days ago:
  2. I started an open source project. This basically for me learning about nokogiri and rails-api, but perhaps other people might find it useful

Ok, if you think you have benefited from the open source community, please consider to give back. No contribution is too small. And it is not only by submitting to open source repository, some other ways, like writing a free access blog post, help too!



A Web Developer Journal