Flux RSS
fév 11

Créer un contrôleur pour les pages statiques dans Rails

Posté Vendredi 11 février 2011 dans Controller, Snippets

  1. 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’
  2. get "/*name", :to => "pages#show"
  3. Créer un controleur PageController avec une action show
  4. 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
    
  5. Créer une structure de pages à l’intérieur de app/views/pages/
  6. app/
    -- views/
    -- -- pages/
    -- -- -- home.html.haml
    -- -- -- contact-us.html.haml
    -- -- -- services/
    -- -- -- -- warranty.hmtl.haml
    -- -- -- -- advices.html.haml
    -- -- -- -- subdir/
    -- -- -- -- -- last_file
    
  7. Accéder aux pages en tapant :
  • rails_app/home
  • rails_app/contact-us
  • rails_app/services/warranty
  • rails_app/services/advices
  • rails_app/services/subdir/last_file
WordPress SEO fine-tune by Meta SEO Pack from Poradnik Webmastera