I\'m creating a mobile site next to our normal html site. Using rails 3.1. Mobile site is accessed in subdomain m.site.com.
I have defined mobile format (Mime::Type.
How can I set that it's always [:mobile, :html] inside the mobile site? Can I set it somehow in the controller already?
Yes.
Here's a simple solution, but it's a bit gross.
class ApplicationController
...
def formats=(values)
values << :html if values == [:mobile]
super(values)
end
...
end
It turns out Rails (3.2.11) already adds an :html fallback for requests with the :js format. Here's ActionView::LookupContext#formats=
# Override formats= to expand ["*/*"] values and automatically
# add :html as fallback to :js.
def formats=(values)
if values
values.concat(default_formats) if values.delete "*/*"
values << :html if values == [:js]
end
super(values)
end
So you can override formats yourself and it will be conceivably no more gross and hacky than the existing Rails implementation.
Where does the self.formats come in views (what sets it originally)
ActionController::Rendering#process_action
assigns the formats array from the request (see action_controller/metal/rendering.rb
)
# Before processing, set the request formats in current controller formats.
def process_action(*) #:nodoc:
self.formats = request.formats.map { |x| x.ref }
super
end
Why isn't it the same as i set in controller before_filter?
It's not the same as what you set in your before_filter because before filters are run before #process_action (as you'd expect). So whatever you set gets clobbered by what #process_action pulls off the request.