2

I'm learning Ruby-on-Rails and doing some homework from school. I need to refactor the default_avatar method.

The logic that I want to accomplish is:

First, check whether the user name is present, and return the default avatar (AVATAR_CATLIKE in this case) if it is not. (this in one line code)

Otherwise, select a default avatar based on the user's name. (this with case statement)

Initially, the default_avatar method was written with nested if and elsif statemen, I've refactored it like this:

Extracted from module ApplicationHelper file:

   def default_avatar(user)
     if user.name.present?
       user
     else
       AVATAR_CATLIKE
     end

     user = case
       when user.name[0].downcase < "h" then AVATAR_CATLIKE <- #line:15 highlighted
       when user.name[0].downcase < "n" then AVATAR_RHOMBUS
       when user.name[0].downcase < "u" then AVATAR_PIRAMID
       else AVATAR_CONIC
     end
   end

This is the test suite:

3   class LogInTest < ApplicationSystemTestCase
4    test 'sign up creates a User' do
5      visit(new_user_path)
6      fill_in('Email', with: 'new_user@gmail.com')
7      fill_in('Password', with: 'password')
8      click_button('Sign up')
9      assert current_path.include?(users_path)
10    end

When runnig the test, it through an error:

ActionView::Template::Error: undefined method `[]' for nil:NilClass
    app/helpers/application_helper.rb:15:in `default_avatar'
    app/views/application/_user_card.html.erb:12:in `_app_views_application__user_card_html_erb___82684501134077429_70123472943620'
    app/views/users/show.html.erb:5:in `_app_views_users_show_html_erb__133265224909210904_70123472923260'

bin/rails test test/system/log_in_test.rb:4

Any hint of how to improve my code and avoid the given error?

Thanks in advance for the help.

1 Answers1

1

I've found a solution, but I'm not sure if it's completely right:

In module ApplicationHelper

def default_avatar(user)
    AVATAR_CATLIKE unless user.name.present?


    case
      when "#{user.name}".downcase < "h" then AVATAR_CATLIKE
      when "#{user.name}".downcase < "n" then AVATAR_RHOMBUS
      when "#{user.name}".downcase < "u" then AVATAR_PIRAMID
      else AVATAR_CONIC
    end
  end

This way everything works.

But if any somebody has another solution, it's welcome to post id.

Thanks