Domain switch

If you are a somewhat regular reader, you have probably noticed that I’ve changed the domain name from babinho.net to berislavbabic.com. Maybe you didn’t notice it at all, kudos for that, because you have been redirected automatically. There were a few reasons for my decision, and I’ll try to sum it here. I won’t go much into details of how to do it, because you already have a lot of information on the Internet covering it. First to explain the babinho moniker. I’ve been using it for a lot of time now. It’s a nickname that dates back to the year 2000, and stems from the obsession with Brazilian football players way back then, when we all had similar nicknames. And mine just stuck around. I wanted to retire it for a long time already, but the more you are invested in something, the harder is it to move away from it. I decided to follow the advice given primarily by John Sonmez in his blogging course, but it is also suggested in many other places, and used by a lot of people I’m following and consider to be internet famous, at least in the small niche that I’m following, e.g. Nathan Barry. As this is a personal technical blog, I decided to go with my name and not some SEO optimised domain name. I believe that personal branding is the corner-stone for each developer, and something everyone, in the tech world or not, should work on as much as possible. There is no better way for you to stand behind your work by stating your name loud and clear. It is professional to the core, and gains you more respect than some childish moniker. It is the scariest thing you can do, because if you make a blunder people will know. But don’t obsess with it, because people rarely or even never remember other people’s blunders. And they will appreciate you more for trying and failing, than for not trying at all. I know that I stood behind that moniker for a really long time, and it has defined my work and sometimes my hobbies. I was not ashamed of my real name, but I just decided not to stand behind it. Going by a nickname was cool and hip, and somewhat unprofessional. Although I’m not saying you shouldn’t use some kind of an alias, especially if you are not allowed/afraid to write because of some repercussions (please do yourself a favour and change the job or the place you live as soon as possible), I am saying that you should use your own name when you engage in technical writing. If you are considering to write or are already writing about really controversial and dangerous stuff, then do everything needed to protect your identity, and be as anonymous as possible. I won’t go into details on how to do that, but there are many privacy oriented websites, so you just have to look around.

On continuous improvement

It is really hard starting something new. Just consider the first time you sat down at the computer to write a “Hello World!” program. Following the tutorial or whatever, you were able to copy/paste or type the code into some IDE or a REPL environment and run it. Then you decided to create “an application” and it was nothing like that Hello World example. Maybe you saw the video on How to create a blog in 15 minutes, and got hooked to this fancy new Ruby on Rails thing like I have. Regardless of the way you started, there is one constant in everything that you do.

If you do something consistently over a longer period of time, you will eventually get really good at it.

Consider blogging, or technical writing for example. Unless you were some kind of a teen writing prodigy, you can’t write that well. Especially if the school system you were a part of didn’t encourage creative writing. I struggled with essays and general writing throughout my school years. And I never thought that writing was a skill that everyone should have. After almost 6 years of on and off blogging, I believe writing to be a really necessary skill, and it really changes the way you express your self, and the way you convey ideas to other people.

Looking back at my posts from 2009, I can’t stop being sad for myself, because of the bad grammar, sentence construction, and even the notion of conveying ideas to people. But it got better over time. I used to struggle when writing 200-300 words in a blog post, and now a 500+ word blog post almost comes naturally.

Gradual improvement is a great thing, and if you hone your skill consistently, you will become an expert in what you do. I know I’m far away from being the next Seth Godin when it comes to writing, but I can try to improve with each post I write, and I can create a habit of writing every day.

You can do the same, choose a skill you want to improve, don’t set any goals or anything, just do it. If it’s writing, make a calendar entry each day and tell yourself to write e.g. 500 words that day. It can even be 100 words, creating a good habit is what matters most, not the amount of doing something.

Don’t set your goals too high, because you will never accomplish them, and you will loose the taste of all those small wins that come when you do get good at something, and realise that you have done something worthy.

There is a great app that I use, and it’s called Commit, and it is probably the best thing I could have done for me. This app, in addition to the Tiny Habits method by B.J. Fogg, was the cornerstone in most of my work.

It is hard to force yourself to sit down and write a 2000+ words blog post, but it is pretty easy to sit down and write 500 words. If you struggle with 500, start with 100. It won’t take you more than a couple of minutes accomplishing that goal, and if you really like what you are writing about, you can always continue. It’s the sitting down (or standing up at a desk) and starting that counts. Make that your daily habit.

You can always do more than the minimum, but set a realistic minimum that you can do each day. And your skills will improve. Of course, they will improve faster if you do it more, but don’t overdo it, because if you burn out, it will be really hard to start again.

Issue with Rails’s restrict_with_exception and counter_cache

When building Rails applications, a lot of focus goes into optimisation. One of those optimizations is using Rails counter_cache columns. The reasoning behind it is simple, you have a relation e.g. Post to Comments and you want to display the comments count for each post. One option is to always count the comments for each post with something like @post.comments.count of course, this is a really expensive operation, and if you are displaying more than one post on the page, it will cause an N+1 issue. Also going to the database just to count how many rows a relation has, isn’t really the best idea.

Luckily Rails has its own optimisation, called counter_cache. It is very simple to include in the model, and Rails manages all of the magic for you behind the scenes. Below is the example of Post and the cached comments count. The only prerequisite that you have to do, is to add a comments_count integer column, with default value of 0.

#in a migration
def change
  add_column :posts, :comments_count, :integer, default: 0
end

class Post < ActiveRecord::Base
  has_many :comments
end

class Comment < ActiveRecord::Base
  belongs_to :post, counter_cache: true
end

This way, via the Rails Magic™, you will get the count column incremented whenever a new comment is posted. And decremented when a comment is destroyed (if you support such a thing). Now you don’t have to count all of the comments when showing the number next to the post, which will be a pretty big performance boost (relatively speaking).

That is the first part of the equation, as the title clearly states this post has something to do about restrict_with_exception. That is the dependency management type, which disallows you to destroy a record that has child records, with that orphaning those records, and creating database inconsistencies. In our case, a post with comments.

We have to modify the Post class to accomplish this:

class Post < ActiveRecord::Base
  has_many :comments, dependent: :restrict_with_exception
end

Now every time you call destroy on a Post model that has comments, Rails won’t let you do that, and it will raise an exception, which is the desired behaviour.

Now, we avoid rails and use regular SQL when the situation needs us to. Let’s say moving comments from one post to another. It can be done with

@post.comments.each do |comment|
  comment.update_attributes(post_id: @new_post.id)
end

But for a post with a lot of comments this operation can be too slow. Moving comments with a sql update is much easier and faster way to accomplish the same thing, but not without it’s own pitfalls. @post.comments.update_all(post_id: @new_post.id) will update your comments and set them to the new post, and you will probably want to refresh the counter_cache on the @new_post, so you have to do something like this Post.reset_counters(@new_post.id, :comments).

Now if you forget doing the same thing on the old post, and just try to destroy it, you will fins yourself chasing ghosts. Rails somehow takes the counter cache column as an authority, before even looking if there are associated records there. This is a cool performance hack, and by going only through Rails, and not pure SQL, this situation wouldn’t happen at all.

Sometimes we can’t or don’t need Rails call backs and validations, just to transfer the ownership from one model to another. Then weird things start to happen, and you don’t know why, so you lose a day debugging what should be a simple thing.

Dynamic components in Ember.js

When building Ember.js apps you will try to avoid code duplication as much as possible. One of the ways of doing that is using Ember components. Components are small, reusable pieces of code, that share a common functionality. For example, you can have a component that shows a user’s Twitter feed, that receives the twitter handle as a parameter.

Components are the new hotness and the way to go with Ember.js 2.0 and they are also being introduced and used in HTML5. Ember components are closely built to adhere to the W3C specification so they should be compatible when the component adoption increases.

Sometimes you want to render a different component in the same place, for example a user’s image and contact info, which can be different for a person and an organisation. So to avoid ugly conditionals in handlebars code there is an option to show components dynamically with the convenient component helper.

You won’t avoid having those conditionals of course, but you won’t have to put them in your handlebars templates, which should be as logic-less as possible. They can reside at the model level, as a computed property. I will simplify this even further and use an example where we will receive the value from our API.

We will be using a simple polymorphic relationship in our API and values returned from ownerType will be “user” and “company” for this example.

Of course we want to show different data for the user and the company, but because we are showing them in the same place, we would have to use a conditional in handlebars to show them. And or model (or controller) should return the isUser boolean. This approach will make future code maintenance a nightmare.

// app/models/owner.js
import DS from 'ember-data';
import Ember from 'ember';

export default DS.Model.Extend({
  name: DS.attr('string'),
  ownerType: DS.attr('string'),
  // ...
  isUser: Ember.computed.equal('ownerType', 'User'),
  // ...
});
{{#if model.isUser}}
  {{owner/user-widget owner=model}}
{{else}}
  {{owner/company-widget owner=model}}
{{/if}}

As you can see, this conditional isn’t really the best one imaginable. If we add another ownerType possibility, we will have to add an additional component (which is the only thing we should be doing), add another boolean on the Owner model, and make the conditional above even more complex than it is. No one probably wants to be remembered by code like this:

{{#if model.isUser}}
  {{owner/user-widget owner=model}}
{{else}}
  {{#if model.isOrganisation}}
    {{owner/organisation-widget owner=model}}
  {{else}}
    {{owner/company-widget owner=model}}
  {{/if}
{{/if}}

There clearly must be a better and cleaner approach. Ember component helper comes to the rescue. And with some clean coding we can avoid all of the conditionals mentioned here.

// app/models/user.js
// ... 
   widgetComponentName: Ember.computed('ownerType', function() {
     return `owner/${this.get('ownerType').toLowerCase()}-widget`;
   });
// ...

This way, the model returns a convenient and usable string when we get the displayComponentName property from it. Now we can use this and have the cleanest possible handlebars template:

{{component model.widgetComponentName owner=model}}

Component helper will resolve the correct component and render it. If a new owner type pops up, the only thing we need to change is to add the widget component for that owner, which is also a great example of separation of concerns, and we are reducing code churn a lot. To reduce the code duplication and complexity you can also take use inheritance to combine similar functionality under one object, and extend it with specific code for each object. I’ve written a blog post about it called Simple Inheritance with Ember.js that you should definitely check out.

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. There are a couple of options while using Ruby on Rails. First one is Prawn which is a pure PDF generator library, and the other options are mostly wrappers around the very popular wkhtmltopdf unix library that converts html pages to pdf. There is also an option that uses PrinceXML but I would initially exclude it because it is pretty pricey for an SME.

While using Prawn gives you all of the formatting power when creating PDF files, it’s learning curve is pretty steep, and the option of converting html to a PDF seems pretty good. This is especially the case when you already have html templates that only need some small modifications to be able to convert them to PDF.

There are a couple of gems that wrap around the wkhtmltopdf library, and ruby-toolbox pdf generation section shows some more viable options that can be used when generating PDF files from ruby.

I’ll be using WickedPdf in this example, as that is the one I have set up this system with a couple of times already, so I’m pretty confident it will work in any other Rails application.

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.

class ThingsController < ApplicationController
  def show
    respond_to do |format|
      format.html
      format.pdf do
        render pdf: "file_name" # Excluding ".pdf" extension.
      end
    end
  end
end

That part was pretty easy, and you can configure the pdf render with a lot of options that are mentioned in the advanced configuration section of the WickedPdf Readme

Generating PDF from ActionMailer

The issue when trying to generate the PDF from ActionMailer is that there is no request, so you have to render the html in a different way. In a nutshell, you want to render the template to a string, and then forward that string (html) to the wkhtmltopdf. This is the same way the gem work when rendering pdf from the controller, but it is worth mentioning once more.

We will use a method that exists on the AbstractController::Rendering and it is called render_to_string So we can do something like this in the mailer:

class TodoMailer < ActionMailer::Base
  #...
  def pdf_attachment_method(todo_id)
    todo = Todo.find(todo_id)
    attachments["todo_#{todo.id}.pdf"] = WickedPdf.new.pdf_from_string(
      render_to_string(pdf: 'todo', template: 'todo.pdf.erb', layout: 'pdf.html'), { :hash_with_wickedpdf_options }
    )
    mail(to: todo.owner.email, subject: 'Your todo PDF is attached', todo: todo)
  end
end

By using this approach, we can easily send a PDF attachment from an ActionMailer method. You can do this for any Rails template you want, but be sure to test everything before putting it into production.