4

One of my clients wants his new Rails application to look more like his traditional web site. He wants to know if I can force urls to have a file extension, preferably .html.

I don't want to hard-code the extension in routes.rb as

match ':controller/:action/:id.html'

(or similar) because the client also wants to have a respond_to-style JSON API which requires the use of .:format.

Can this be done?

Moshe Katz
  • 15,992
  • 7
  • 69
  • 116

2 Answers2

6

Just as Mattias Wadman suggested, in config/application.rb add:

AppName::Application.default_url_options = { :format => "html" }

But also change config/routes.rb to:

root :to => 'pages#home', :defaults => { :format => "html" }
Eden Townsend
  • 395
  • 1
  • 6
2

Im no Rails routing expert but I tried to force HTML format by changing the default URL options and at least the URL helpers seams to generate .html URLs now, it's a start.

config/application.rb (at the bottom)

AppName::Application.default_url_options = {:format => "html"}
Mattias Wadman
  • 11,172
  • 2
  • 42
  • 57
  • Hmm seams to work for me, weird. do you see ...(.:format) for your routes when running `rake routes`? – Mattias Wadman Dec 06 '11 at 19:13
  • Output of `rake routes`: `/:action(.:format) {:controller=>"pages", :action=>":action"}` and `root / {:controller=>"pages", :action=>"home"}`. (I can't break it up onto multiple lines in a comment.) Using `link_to ...` works but using `<%= root_url %>` returns `http://server:3000/?format=html` – Moshe Katz Dec 06 '11 at 22:06
  • If you look at the source for the [root](http://apidock.com/rails/ActionDispatch/Routing/Mapper/Base/root) route match you will see that it does not include `:format`. But you can replace it with `match '/(.:format)', :to => 'pages#root', :as => :root` etc. But then `root_url` will be `"http://www.example.com/.html"`, probably not what you want? – Mattias Wadman Dec 07 '11 at 11:56
  • That's not what I want but I could just not use `root_url` and redirect `/` to `/home.html` instead. – Moshe Katz Dec 07 '11 at 16:04
  • Thanks for the help. I want to give it until the end of the week to see if anyone else has any ideas. If not, I'll mark this as the answer. – Moshe Katz Dec 07 '11 at 21:16