Chinu Chinu - 4 months ago 13
Ruby Question

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="<%=root_path+SiteConfiguration.gallery_path+@gallery.image %>" 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?


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="" />