fév 11
Créer un contrôleur pour les pages statiques dans Rails
Posté Vendredi 11 février 2011 dans Controller, Snippets
- Catcher toutes les requêtes avec un Glob dans routes.rb (dernière route), avec name le nom de la page pouvant contenir un chemin du type ‘services/home’
- Créer un controleur PageController avec une action show
- Créer une structure de pages à l’intérieur de app/views/pages/
- Accéder aux pages en tapant :
get "/*name", :to => "pages#show"
class PagesController < ApplicationController
def show
ext = ".html.haml"
dirname = File.dirname(params[:name])
filename = File.basename(params[:name] + ext)
Dir.chdir(File.join(RAILS_ROOT, "app", "views", "pages"))
static_pages = Dir.glob(File.join(dirname, "*" + ext))
raise "404" unless static_pages.include?(File.join(dirname, filename))
@message = "Welcome to #{params[:name]}"
render File.join("pages", dirname, filename)
end
end
app/ -- views/ -- -- pages/ -- -- -- home.html.haml -- -- -- contact-us.html.haml -- -- -- services/ -- -- -- -- warranty.hmtl.haml -- -- -- -- advices.html.haml -- -- -- -- subdir/ -- -- -- -- -- last_file
- rails_app/home
- rails_app/contact-us
- rails_app/services/warranty
- rails_app/services/advices
- rails_app/services/subdir/last_file