1

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

app/controllers/concerns/site_configuration.rb

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

config/environment.rb

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/'

app/views/galleries/index.html.erb

<img src="<%[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?

1
  • Just don't send nil variables to your erb, check it before! Commented Jun 1, 2016 at 9:15

1 Answer 1

2

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:

config/settings.yml:

---
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="" />
Sign up to request clarification or add additional context in comments.

4 Comments

missing SiteConfiguration.gallery_path in my image path. Please check <img alt="Dsc 0380" src="/DSC_0380.jpg">
My Image path should be- <img alt="Dsc 0380" src="/uploads/gallery/DSC_0380.jpg">
I saw you updated answer. Let me know how to print my settings.yml gallery_path in my view(erb) file?
Yes I just generate config file. Now working fine. No need SiteConfiguration Thank you dear.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.