Saturday, April 30, 2016

Conditional partials with Devise gem

A common problem web developers face is the fact sometimes we need to show parts of a view only for logged (or non-logged) users. The most common situation is when you need to have a login button/link in your main page.

If you are using Devise gem for authentication this turns out to be a very simple matter. You just have to use the devise helper user_signed_in?. This helper returns true if there is a logged user and false otherwise. It may be used in your controllers, model or views.

In a view you may have something like

<% if user_signed_in? %>
    <%= render 'your_conditional_partial_name' %>
<% end %>

By the way... I know this is a bit off-topic for this post, but since we are talking about views and about embedded Ruby code, let me say a few words about a common confusion.

This week I saw a question at StackOverflow (unfortunately  I haven't the link right now) where a guy was presenting a common problem. He wrote in one of his views something like:

<%= @users.each |user| do %>
    # Some code to show user's fields
<% end %>

And he was complaining that after the user data his view was showing a Hash with all the values of the records.

The point here is that he used <%= %>, with the =, instead of only <% %> in his block opening. Ruby interpreted this as a request to show the contents of the variable inside the tags. So, I give you a free advise: Don't use the = in conditionals or block opening statements. This is one of those errors easy to do and hard to find.

Sunday, April 24, 2016

Always study the standard libraries (2)

Here we have another example of the importance of the standard libraries. It all started with this question here, posted at StackOverflow:

The code given by the OP could be fixed, but it had some problems. The main one is the fact it is too particular. It had lines like 

while row.length >= 13

This makes it specific to solve the problem proposed for a single value (13). This is something we must avoid at all costs. Never write code tar particular. It is not worth the effort. In a purely theoretical problem like this one can't see this easily. But if you do that in a system designed for production you'll regret it the first time you need to perform a maintenance.

Then I suggested this code, more generic but basically with the same structure:

sequence = "73167176531330624919225119674426574742355349194934

## This will remove all \n
seq ="\n","")

def multiply_arr(a)
    prod = 1
    a.each do |f|
        prod = prod * f.to_i    

def max_product(s,n)
    max = -1
    lim = s.length - n
    (0..lim).each do |pos|
        ns = s.slice(pos,n)
        arr = ns.each_char.to_a
        prod = multiply_arr(arr)
        max = (prod > max) ? prod : max 

Good code. Works fine. It is more generic than the code given by the OP. But...

The user Jörg W. Mittag proposed the following code:

def max_product_subsequence(sequence, subsequence_length)
        gsub(/\s+/, ''). 
        map {|subseq| subseq.reduce(:*) }. 

As you may see, this code does the same mine does, but is is much shorter and much more efficient. I benchmarked it and the execution time is much better.

This is a great example of the importance of the standard libraries. Core Ruby provides wonderful functionalities, if you know it well and apply whenever it is possible.

Ah... before I forget... People say good programmers are always lazy. They need to be lazy in order to try to always find the easiest way to do things. But this does not include being lazy to rewrite code.

Never believe your code is good. Always try to find another way to rewrite it. 

Saturday, April 23, 2016

Always study the standard libraries

I was faced with a common problem: given an [a-z] string, find out the most common letter inside it and the number of times it appears.

My first solution was very simple, indeed:

def most_common_letter(string)
    h =
    characters = string.chars
    characters.each do |c|
        if (h[c].nil?) then
            h[c] = 1
            h[c] = h[c]+1
    maxk = nil
    maxc = -1
    h.each do |k,v|
        if (v > maxc) then
            maxk = k
            maxc = v
    [maxk , maxc]

It works, but it is too big and we may do some changes to make it smaller and a bit more efficient.

def most_common_letter(string)
    h = { |c|
        h[c] = 0 if (h[c].nil?)
        h[c] = h[c] + 1
    maxk = nil
    maxc = -1
    h.each do |k,v|
        if (v > maxc) then
            maxk = k
            maxc = v
    [maxk , maxc]

As you may see, here I omitted the unnecessary variable characters and applied all transformations directly from string.

Besides, I used an if construction to initialize all elements the hash h with 0 when they are created. h[c] = 0 if (h[c].nil?) created h[c] and initializes it with 0 if the hash has no such key as c. With this we replaced five lines with only two.

A better solution, of course, but still a bit big for Ruby standards. Now let's see what happens when we really use Ruby standard libraries.

def most_common_letter(string)
    counts =
    string.each_char {|c| counts[c] += 1 }
    counts.max_by{|k,v| v}

Here we take advantage of the fact Hash provides for a default value. When I say counts =, I'm telling Ruby to initialize all new elements of the hash counts, whatever the key, with 0. Then we use the each_char block to populate the hash counts, whose keys are the letters and the values are the counts of the corresponding letters. Finally we use the max_by method, which counts inherits from Enumerable, to return the key => value pair with the highest count.

As you may see, just by knowing how to use the default libraries one may simplify the code a lot, making it more efficient too. A great reason to read Ruby's documentation carefully and apply what you learn there.

Friday, April 1, 2016

Learn how to use Devise gem well

There are lots of tutorials about Devise gem, explaining how to install it, how to create the views and how to generate the model used to authenticate in your application. If you are just looking for this, please don't waste your time reading this article. Just watch this video and you'll learn the basics.

But if you are facing a particular issue when using Devise gem in your Rails application, this article is going to show you deal with it.

My Rails application must insert, update and delete the objects described in Devise model

Let's understand the problem first.

Assume you have an entity named User in your system and this is the entity Devise will authenticate. In other words, users log into your app.

When this happens, the structure of Devise is prepared to create (register) new users, update them, remove them... Well, Devise is prepared to fully control users in your app. But...

But, what happens if logged users are allowed to register other users?

Devise assumes a user tries to register only when it not logged. Register is a requisite to log into an app, then one is not supposed to register (create a new user) when logged! Then, if you try to create a new user when a user is already logged, you'll receive a :require_no_authentication error, will be redirected from your register method to another place and the registration will fail.

A friend of mine gave up using Devise after facing this issue. And I saw many people asking about this at StackOverflow. It is really a bothering thing! I suffered this myself and researched a lot before finding this solution I'm going to show you. I even restarted a system from zerro, just because I thought Devise should never be user over a pre-existing model, but this is not true.

So, let's correct all this stuff in easy steps:

(We are going to assume we are using User as our authentication model, but all these steps are similar if you use Admin or Contact or any other model. You must only do the appropriate changes.)

1) Create new methods

Still assuming you are authenticating User, go to app/controllers/UsersController.rb and create new method called user_new, user_create and user_update. Copy the contents of new, create and update, respectively, to these methods;

2) Copy app/views/users/new.html.erb to app/views/users/user_new.html.erb;

3) Copy the partial app/views/users/_form.html.erb to app/views/users/_user_form.html.erb;

4) Edit app/views/users/new.html.erb and app/views/users/edit.html.erb to render the new partial, i.e., change

<% render '_form' %>


<% render '_user_form' %>

5) In the partial _user_form.html.erb change the line

form_for @user


form_for(@user, url: '/users/user_create'

6) Now, edit config/routes.rb and right below the line who reads

devise_for :users

create scoped routes for the new methods you created

  devise_scope :user do
    get   'user/user_new', to: 'users#contact_new'
    get   'user/user_edit/:id', to: 'users#user_edit'
    post  'user/user_create', to: 'users#user_create'
    patch 'user/user_create/:id', to: 'users#user_update'

Now we are ready to, even logged, create and edit users in a Devise authenticated app. But if you have user parameters beyond those used by devise, i.e., if you  want users to have fields like :name, :address or something like that, don't forget to permit these parameters in your Users controller.