Force absolute URLs in views throughout a response

Posted Over 13 years ago. Visible to the public.

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 Show archive.org snapshot for traits.

Arne Hartherz
Last edit
Almost 12 years ago
License
Source code in this card is licensed under the MIT License.
Posted by Arne Hartherz to makandra dev (2010-08-24 17:28)