Namespace vs. Scope

I’ve often asked myself what exactly the difference between namespace and scope is.

Namespace

This is the simple option. It will prefix the generated path and the path name. And it also assumes that the controller is to be found under a module named in the same manner as the namespace itself.

namespace :management do
  resources :users
end

Generated routes:

Prefix Verb      URI Pattern                            Controller#Action
management_users GET    /management/users(.:format)     management/users#index
                 POST   /management/users(.:format)     management/users#create
management_user  GET    /management/users/:id(.:format) management/users#show
                 PATCH  /management/users/:id(.:format) management/users#update
                 PUT    /management/users/:id(.:format) management/users#update
                 DELETE /management/users/:id(.:format) management/users#destroy

Scope

Scope can give you a more accurate result but is a bit more complex at the same time.

Without options

When using scope without any options and only a scope name, it will just add a prefix for the generated path.

scope :management do
  resources :users
end

Prefix Verb   URI Pattern                Controller#Action
 users GET    /management/users(.:format)     users#index
       POST   /management/users(.:format)     users#create
  user GET    /management/users/:id(.:format) users#show
       PATCH  /management/users/:id(.:format) users#update
       PUT    /management/users/:id(.:format) users#update
       DELETE /management/users/:id(.:format) users#destroy

With option: module

“module” lets you define another module and only the module.

scope module: 'management' do
  resources :users
end  

Prefix Verb   URI Pattern          Controller#Action
 users GET    /users(.:format)     management/users#index
       POST   /users(.:format)     management/users#create
  user GET    /users/:id(.:format) management/users#show
       PATCH  /users/:id(.:format) management/users#update
       PUT    /users/:id(.:format) management/users#update
       DELETE /users/:id(.:format) management/users#destroy

With option: path

“path” will prefix the generated path

scope module: 'management', path: 'fu' do
  resources :users
end

Prefix Verb   URI Pattern             Controller#Action
 users GET    /fu/users(.:format)     management/users#index
       POST   /fu/users(.:format)     management/users#create
  user GET    /fu/users/:id(.:format) management/users#show
       PATCH  /fu/users/:id(.:format) management/users#update
       PUT    /fu/users/:id(.:format) management/users#update
       DELETE /fu/users/:id(.:format) management/users#destroy

With option: as

“as” can be used to change the name of the path method used to identify the resources.

scope module: 'management', path: 'fu', as: 'awesome' do
  resources :users
end   

Prefix Verb   URI Pattern                    Controller#Action
awesome_users GET    /fu/users(.:format)     management/users#index
              POST   /fu/users(.:format)     management/users#create
awesome_user  GET    /fu/users/:id(.:format) management/users#show
              PATCH  /fu/users/:id(.:format) management/users#update
              PUT    /fu/users/:id(.:format) management/users#update
              DELETE /fu/users/:id(.:format) management/users#destroy

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 %>
    </div>
  </div>
</div>

Handle simple remote modal dialogs in rails applications

I will show you how to handle simple remote modal dialog rendering in rails apps.

Sometimes we do not want to write big javascript applications to have working remote modals in our rails applications. And rendering modals on the client is to bit of a hassle? Why not let the server (fastest html renderer in town) respond with complete dialogs?

Iam using Bootstrap Modals for this example. But it will work for any JS modal library.

Step 1 – Add a new modal layout.

<!-- app/views/layouts/modal.html.erb -->
<div class="modal fade" tabindex="-1" role="dialog">
  <div class="modal-dialog">
    <div class="modal-content">
      <%= yield %>
    </div><!-- /.modal-content -->
  </div><!-- /.modal-dialog -->
</div><!-- /.modal -->

We also need to define a place where the dialogs will be rendered. Add the following to the application layout file.

<!-- app/views/layouts/application.html.erb -->
<div id="modal-holder"></div>

Step 2 – Add modal javascript

This will enable links with data-behavior=”modal” attribute to be rendered in modal windows.

$ ->
  modal_holder_selector = "#modal-holder"

  $(document).on "click", "[data-behavior='modal']", ->
    $('body').modalmanager('loading')
    location = $(this).attr("href")
    $.get location, (data)->
      $(modal_holder_selector).html(data).find(".modal").modal("show")
    false

  $(document).on "ajax:success", "[data-behavior='modal-form']", (event, data, status, xhr) ->
    # make sure this event is observered by document and not by dom node itself.
    url = xhr.getResponseHeader("Location")
    # Navigates to given location header in http response or closes the modal handler.
    if url
      window.location = url
    else
      # FUTURE TODO: make sure only the modal which was called last will be destroyed.
      $(".modal").modal("hide")
    false

Step 3 – Modify controller action

Now change the render layout for the controller action like so:

class ApplesController < ApplicationController
  def new
    @apples = Apple
    render layout: 'modal'
  end
end

Step 4 – Use it

<%= link_to 'Create apple', new_apple_path, data: { behavior: 'modal' } %>

Please make sure the rendered form will have a data-behavior=”modal-form” attribute to successfully close the dialog after valid ajax response.

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:

en:
  active_record:
    models:
      webinar_presenter:
        one: Webinar presenter
        other: Webinar presenters
    attributes:
      webinar_presenter:
        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

Pagination

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!

Indexes

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.

Bullet

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
end

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
end

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
end

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 }
end

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.

BEM! Tackle your growing CSS with a Pattern that just works

As i worked on a big project for my job, we came to the conclusion, that just using the Twitter Bootstrap CSS Framework with some view specific CSS code is not enough.

This all resulted in some big assets folders with a huge load of files which prevented any kind of good maintainability. BEM, meaning Block, Element, Modifier, is a front-end methodology developed at Yandex.

It is important to note that the naming techniques covered in this post are not the original BEM ones, but are altered versions that I much prefer. Whatever actual notation is used, they are all based on the same BEM principles.

.block {}
.block__element {}
.block--modifier {}
.block__element--modifier {}
.long_block_name {}

There are basically three groups:

  • .block: the root block component
  • .block__element: a part of a block component
  • .block--modifier: a variant, modification, extension of a component block (can also be aplied to an element)

Elements are delimited by two underscores. Modifiers are delimited by 2 hyphens. Long block names are delimited by one underscore. This has the advantage that you can select the classes better by a double click.

The whole point is to improve readability by other developers, so you can tell what the markup is doing by the name alone.

Let me give an example. You probably all know the .media element from different kinds of CSS Frameworks.

.media {}
.media__img {}
.media__img--right {}
.media__body {}

<div class="media">
  <img src="image.png" class="media__img media__img--right" alt="awesome image"/>
  <div class="media__body">
    <h2><!-- title --></h2>
    <p class="lead"><!-- some lead text --></p>
  </div>
</div>

Now we can see, that .media is a block and .media__img is a element with a modification or extension .media__img--right. The class .lead has nothing to do with our component. This is very helpful.

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 %>"