Read more

Force absolute URLs in views throughout a response

Arne Hartherz
August 24, 2010Software engineer at makandra GmbH

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

Illustration web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
Read more Show archive.org snapshot

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
August 24, 2010Software engineer at makandra GmbH
Posted by Arne Hartherz to makandra dev (2010-08-24 19:28)