Handle Git Patch Apply Conflicts

Sometimes I update a repository of a customer with the newest version of our software and I made some really small changes in the code only for this customer. I usually stash those changes, checkout the newest version and then apply the changes again.

Sometimes conflicts apply from that stash apply. Here is a solution on how to fix it without committing anything:

  1. Save the stashed changes
  2. Unstage the merge conflicts: git reset HEAD .
  3. Apply them manually

Any better ideas??

Rails Radio Button Mystery

Once I have to handle radio buttons in rails, I always need to look up the syntax again – especially of the attributes. So I wanted to print the most important issues down:

At first, we need to know how the normal html radio button behaves. A radio button is an input field with type radio with the following attributes:

  • name: Individual name of the radio button. If many have the same name, they belong to the same group.
  • value: value that is send when submitting the form
  • checked: if the value is checked when loading the page or not

Now looking at the rails function we have the following attributes to the radio_button function:

  • object_name: name of the object that should be set
  • method: name of the method that should be set
  • tag_value: value that should be set
  • options: can set checked: true

Irritating is, that if you use f.radio_button on a form, the object_name parameter is automatically assigned and you only have to specify the other parameters.

Example in bootstrap together with a label:

<div class="form-group">
  <div class="col-sm-8 col-sm-offset-2">
    <div class="radio-inline">
      <% CalendarColor.find_each do |calendar_color| %>
          <%= f.label calendar_color.id do %>
              <%= f.radio_button :color_id, calendar_color.id, checked: calendar_color.default_color %> <%= color.name %>
          <% end %>
      <% end %>

Nano Editor helpful commands

Once you open the nano editor on a system I have some commands I always forget and never find in google once I need them. Here they are:

  • CTRL + v: jump to the next page
  • CTRL + y: jump to the previous page
  • CTRL + w + v: jump to the last page (especially helpful for MAC users because the alias ‘CTRL + Shift + ALT + 7’ does not work)
  • CTRL + k: store line in buffer (can be reinserted with CTRL + u)
  • CTRL + x: exit nano

Rails Model Translations

As described in the Rails Guides for translating Active Record Models, you can use the methods Model.model_name.human and Model.human_attribute_name(attribute) to transparently look up translations for your model and attribute names.

This becomes very handy when you use form_for in Rails. You do not even have to write Model.human_attribute_name(attribute) because its content will be loaded automatically. Example:

Your active record model i18n file might look like this:

        one: Webinar presenter
        other: Webinar presenters
        webinar_id: Webinar
        presenter_email: Presenter email

Then this will automatically load the depending attribute names for the set locale:

<%= form_for @webinar_presenter do |f| %>
  <%= f.label :presenter_email %>
  <%= f.text_field :presenter_email %>
<% end %>

Because we had to translate some projects I wrote the I18n Model Translator Gem a little gem that has some rake tasks available to generate those i18n model files automatically for the english language, given that you have used descriptive column names for you models. Feedback is very welcome.

Rails 4 Performance Tips

There are many tools out there that help you improve the performance of you rails apps. In this post I want to introduce you to some of them that help me out most of the time. What I suggest you to do when profiling your rails app is keeping score of the times that you improve. In your rails console log you will see the time the rending took (split into view and activerecord and total time). Rendering time


First thing you should be doing is a pagination. It does not matter how fast your application performs when you have too many records that you are loading. So have a look at any of the good pagination gems out there like will_paginate or kaminari. A good effect is that your application becomes not only faster but your usability also improves a lot!


Next try to improve you indexes for your rails app. Make sure to always index your foreign keys in your database. This creates a foreign key without an index:

rails g migration CreateCalendarEvents user_id:integer

This is the better approach which automatically creates add the index to the migration file:

rails g migration CreateCalendarEvents user:references

Here you see a migration file with the reference to the user model and an automatically created index, with index: true.

index in migration

Sometimes you forget to index all foreign keys. There is a good gem to find out if you did that called lol_dba. With rake db:find_indexes it will find out if there are any indexes missing and create you directly a migration file.


The bullet gem will give you the help with N+1 Queries and Counter Caches.

The N+1 Query Problem is when you for example loop 10 client objects in your view and access the address of the client that is in a different model. Example from here.

clients = Client.limit(10)

clients.each do |client|
  puts client.address.postcode

The problem lies within the total number of queries executed. The code executes 1 (to find 10 clients) + 10 (one per each client to load the address) = 11 queries in total. The solution to this problem is adding an includes in your controller. So in the example write

clients = Client.includes(:address).limit(10)

clients.each do |client|
  puts client.address.postcode

The bullet gem makes sure you do not forgot about the N+1 Queries and gives you a warning when you do.

It will also advice you to use counter caches sometimes. Once you have some counts of records on a model e.g. a Class has_many Students, you want to show that number. Rails can automatically keep the count of the Students to a class via a counter_cache column. Read more on this here.

Rack Mini-Profiler

Rack Mini-Profiler together with flamegraph help you see in detail about the queries performed on a page. You can use it both in development mode and in production. It shows the rendering time of the page at the left upper corner of your screen. When you click on it you see more detailed data. Rack Mini-Profiler. This is a very good way to see how long exactly your database queries take or the views to render.

Regression Tests, Rspec and Rails

This is a guest post by Erwin:
When i first started to work with Ruby on Rails the terms “Behaviour Driven Development” and “Test Driven Development” have been used in nearly every tutorial and screencast. Soon i realized that testing your code is mandatory to build reliable software. Until then, testing was just optional and as many of you know very tedious. Even the setup of your test suite can be hard to accomplish if your application has a complex structure (consider dataflow logic, modeling logic or even time-based logic). Luckily Rails has a bunch of easy-to-use libraries (gems) to test your application.

A popular gem for testing your Rails applications is rspec. Just add the rspec-rails gem to your Gemfile and run the provided installer and you are good to go to test your Rails application. As mentioned before testing can be very tedious due to the fact that a lot of test-scenarios are repeated with a slightly different parameter or environment and even with rspec and the DRY philosophy repetition of code cannot be eliminated completely.

To bring up an example let’s consider the following ActiveRecord model:

# == Schema Information
# Table name: foos
#  id               :integer          not null, primary key
#  title            :string(255)
#  bar_id           :integer
#  account_id       :integer
#  created_at       :datetime
#  updated_at       :datetime
class Foo < ActiveRecord::Base
    # === Relations ===
    belongs_to :bar
    # === Validations ===
    validates :title, presence: true, length: {maximum: 255}, allow_blank: false
    validates_presence_of  :bar

This model has only one relation to another model called :bar and two validation methods that ActiveRecord provides.
The question is do we need to test this model and if we do what would the test or spec look like?

Well, we could rely on ActiveRecord and assume that it executes properly and that ActiveRecord has its own tests to make sure that those validation methods and relations are not broken and in fact ActiveRecord has those tests. So what we don’t want is to test ActiveRecord again. We want to abstract from that and capture the behaviour of our model into a test or spec. This captured behaviour then can be used to inform us about changes to a model and how those changes can possibly afflict other models.

Consider a scenario where we would delete the Bar model and didn’t think about the Foo model that it has still a relation to it. The worst case of this scenario would be that your shipped software crashes and your client payed for a broken software. To avoid this case we could apply regression based testing. Regression testing is a type of software testing that seeks to uncover new software bugs, or regressions, in existing functional and non-functional areas of a system after changes such as enhancements, patches or configuration changes, have been made to them.

The intent of regression testing is to ensure that changes such as those mentioned above have not introduced new faults.

describe Foo do
    it { is_expected.to belong_to :bar }

As we can see our test sample is not very complicated and does not test a complex behaviour of our system but it can give us feedback about our structure and ensures us that the relation :bar exists. Such feedback can be very useful, if used in combination with continuous integration tools like jenkins or travisCI. A drawback of such tests would be that every test case needs to be written manually and depending on the model there would be a lot of test cases that are similar in their structure. So we are in need for an automated approach to somehow generate this test cases and update them when we apply changes to our model.
To solve this issue a rails generator was used to create specs based on relations, validations and their database counterpart. This generator then was put into a gem and published on github (https://github.com/ndea/regressor).

I enjoy your feedback and comments! Thanks.

Rails with Chart.js

I am using Chart.js as a library to show responsive charts on some websites. One of a cool new features is the tooltip. When using it, you usually have to override its behaviour a little bit. So there is this kind of language you can use:

tooltipTemplate: "<%=label%>:<%= value %>"

You see the problem? Rails tries to interpret the <%= %> and there is no existing variable in ruby defined. So it throws an error.

The solution I found was clearly easy but hard to find:

use <%% (double %) instead in your erb, then it will skip.

tooltipTemplate: "<%%=label%>:<%%= value %>"

I18n Rails – How to organize your locales in larger projects

As our rails projects grow bigger and bigger, the i18n locale files easily get messy and will loose their structure after a while. Especially when you have multiple software developers work on the same project.

So we develped a solution for us that is easier to handle and to maintain. The starting point is from the ruby on rails guides combined with this blog post:

We separated our yml files to the folders given by the rails structure. The yml files themself are also structured that way. This is a bit more efford in the beginning, but it is very nice to maintain, because you always know, where you have to put your locales and always know where to look for them!


Each file now only handles the content of one logical controller unit. The views/surveys files now have the content for each action. We group them in the action to logical groups that always look the same. We have a title, the breadcrumbs and then we have a unit for each form.

          text: :defaults.surveys
            text: :defaults.surveys
              placeholder: 'Search surveys...'
                text: 'Search'
                label: 'Topics'
                  placeholder: ''
                label: 'Title'
                  placeholder: ''
          text: :views.defaults.search
          disable_with: :views.defaults.form.searching

The problem with a solution like that is, that you have lots of redundant data. Take breadcrumbs for example. In each views folder there are different actions that have the same breadcrumb navigation. But there is a nice feature that you can use for that:

We put all business dependend locals into the defaults or views/defaults folders and reference them with e.g. :defaults.surveys. That makes it easy to have on each page every element, that can be translated to each language, but also removes redundant translations. But if you come to a language that make it harder to translate everything with the same translation you can translate that one separately!! Which can be quite important for example for languages like chinese.

Why Ruby on Rails

Why Ruby on Rails

I am writing software about 10 years by now. The last 3 years I was delighted by the great web application framework Ruby on Rails, which I don’t want to miss anymore. I want to publish articles in this blog every now and then and will mostly write about this awesome framework. So I want to tell you some good reasons, why I like to use it:

  1. Rails is good for rapid prototyping
  2. Ruby is easy to learn
  3. Rails code is easy to read because of the given structure

Rapid prototyping with Rails

I originally come from the java world. Setting up a new project got easier over the years but it is no comparison on what rails can do. Most blog posts I read when I started learning rails were about scaffolding. Scaffolding is a fast and easy way to create CRUD model/controller/view from scratch.

I usually do not use scaffolding in my working projects anymore, because they usually create a big overhead, but I just love that feature when it comes to a rapid prototype. A first version of our tutorize.com website was created in rails. It was not beautiful, not secure and not even close to be finished, but we had something to show to investors and possible customers. Lot of startup authors say that is the approach that works best for creating businesses without spending lots of money and time and then creating something that nobody even cares about. And I completely agree with it!

Ruby is easy to learn

I just have to say this: Ruby is a quite elegant language. If you have not tried it yet, try it. And the Rails framework is just

Rails code is easy to read because of the given structure

Rails comes with a given MVC-Pattern structure. It is really easy for other developers to dig into someone elses code because of that structure. You know where you find your models, your controllers and views and you know where the urls are build, etc. Very helpful!

And there is also the given structure of the rails engines. I started working with them a while ago and I can also say that this structure helps to understand the code of someone elses engine.

There are lots of features that I could take about right now, but I will leave some space for more posts to come. So try rails and keep on reading.