views:

53

answers:

1

I require nested subdirectories in my sinatra app, how can I simplify this repetitive code?

# ------------- SUB1 --------------
get "/:theme/:sub1/?" do
    haml :"pages/#{params[:theme]}/#{params[:sub1]}/index"
end

# ------------- SUB2 --------------
get "/:theme/:sub1/:sub2/?" do
    haml :"pages/#{params[:theme]}/#{params[:sub1]}/#{params[:sub2]}/index"
end

# ------------- SUB3 --------------
get "/:theme/:sub1/:sub2/:sub3/?" do
    haml :"pages/#{params[:theme]}/#{params[:sub1]}/#{params[:sub2]}/#{params[:sub3]}/index"
end

# ------------- SUB4 --------------
get "/:theme/:sub1/:sub2/:sub3/:sub4/?" do
    haml :"pages/#{params[:theme]}/#{params[:sub1]}/#{params[:sub2]}/#{params[:sub3]}/#{params[:sub4]}/index"
end
A: 

You can use splat parameters:

get "/:theme/*/?" do
  haml "pages/#{params[:theme]}/#{params[:splat].to_s}/index".to_sym  
end
John Topley
Thanks! Though should be `haml : "`
Dr. Frankenstein
The `to_sym` method will convert the string to a symbol. I've updated the answer.
John Topley
Ah ok, cool, both work
Dr. Frankenstein