[Solved] How to fix “no implicit conversion of nil into String” in Ruby

I am developing one small web application in my local machine. I want to set my some common information globally.
Here is my code:


module SiteConfiguration
  mattr_accessor :site_name
  mattr_accessor :banner_path
  mattr_accessor :avatar_path  
  mattr_accessor :gallery_path  
  mattr_accessor :category_path  


SiteConfiguration.site_name = 'Site Name Here'
SiteConfiguration.banner_path = 'uploads/banners/'
SiteConfiguration.avatar_path = 'uploads/avatar/'
SiteConfiguration.gallery_path = 'uploads/gallery/'
SiteConfiguration.category_path = 'uploads/category/'


<img src="<%=r[email protected] %>" alt="" />

Here is I am getting error message

TypeError in Galleries#index

Showing D:/xxx/project/app/views/galleries/index.html.erb where line #1 raised:

no implicit conversion of nil into String

Above code working fine. But one big problem is whatever changes I made every time there is a need to restart the server.

If I restart server then its working fine. After few min if need any changes I am getting same error message. Let me know what is the problem there?

Solution #1:

You can use lazy evaluation to string:

<img src="<%= "#{root_path}#{SiteConfiguration.gallery_path}#{@gallery.image}" %>" alt="" />

but be better to make sure, why exactly one of the field becomes nil? Also move the code to helper or decorator.

To make configuration customizable use config gem. So you will have just a YML-file:


site_name: 'Site Name Here'
banner_path: 'uploads/banners/'
avatar_path: 'uploads/avatar/'
gallery_path: 'uploads/gallery/'
category_path: 'uploads/category/'

So here you have to use Settings constant instead of SiteConfiguration:

<img src="<%= "#{root_path}#{Settings.gallery_path}#{@gallery.image}" %>" alt="" />
Respondent: ???? ????????

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Leave a Reply

Your email address will not be published.