Faery
Faery

Reputation: 4650

Sinatra: put some of my helpers in separate folder

I have a Sinatra app and I have some helpers and they have their folder (helpers) in which I have website_helpers.rb and so on. I want to move some of this helpers in their own folder inside the helpers folder: to have helpers/subhelpers, bacause the files I want to put in the subhelpers folder are different from the others and it makes sense to have a different folder for them.

I tried adding this to my config.ru

Dir.glob('./helpers/subhelpers/*.rb').each { |file| require file }

And then in the controller I have:

helpers MyHelperFromSubHelpers

but I get an error uninitialized constant (NameError).

Any ideas how to fix this so that to have a clear structure?

Upvotes: 0

Views: 235

Answers (1)

ian
ian

Reputation: 12251

TBH, it sounds like you're overdoing it, there's always Rails if you want to go in for a more Java like every-namespace-must-be-a-directory layout. Aside from that, usually, helpers in separate files are placed in the Sinatra namespace - see http://www.sinatrarb.com/extensions.html#extending-the-request-context-with-sinatrahelpers

Personally, I put them in:

project-root/
  lib/
    sinatra/
      name-of-extension.rb

Mainly because if the extension is really useful, I'll end up wanting to use it in another project, and this is the standard layout for a Sinatra gem, which makes it easy to extract it into one and with barely any change in the calling code.

Dir.glob will only return the file name and not the full path with each match, so you need to add the path:

Dir.glob('./helpers/subhelpers/*.rb').each do |file|
  require File.expand_path File.join( File.dirname(__FILE__), "./helpers/subhelpers/", file)
end

will probably fix it.

Upvotes: 1

Related Questions