Posted over 9 years ago. Visible to the public.

Force absolute URLs in views throughout a response

This is more tricky than it should be because url_for, asset_path, etc. all rely on different mechanisms.

Anyway, you can use the attached trait like this:

class ExampleController < ApplicationController does 'host_enforcement', :for => 'some_action' end

Short explanation:

  • asset_host is used for links to stylesheets and javascripts
  • asset_host belongs to ActionController::Base – changes are persistent and will not be reset after a request
  • rewrite_options is used by the ..._path methods in the views
module HostEnforcementTrait # Include this method in a module because we cannot yield out of define_method module InstanceMethods private # Force URLs for JavaScript and Stylesheet links def assets_have_urls old_asset_host = asset_host self.asset_host = HOST yield ensure self.asset_host = old_asset_host end end as_trait do |*args| include HostEnforcementTrait::InstanceMethods options = args.first || {} methods = options[:for] around_filter :assets_have_urls, :only => methods private # Force URLs for link_to etc define_method :rewrite_options do |*args_options| options = args_options.first || {} enforce = methods.nil? || Array(methods).collect(&:to_s).include?(action_name) super(enforce ? options.merge(:only_path => false) : options) end end end

You need modularity for traits.

Growing Rails Applications in Practice
Check out our new e-book:
Learn to structure large Ruby on Rails codebases with the tools you already know and love.

Owner of this card:

Arne Hartherz
Last edit:
over 7 years ago
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Arne Hartherz to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more