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 toActionController::Base
-- changes are persistent and will not be reset after a request -
rewrite_options
is used by the..._path
methods in the views
^
module HostEnforcementTraitInclude 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::InstanceMethodsoptions = 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.
Posted by Arne Hartherz to makandra dev (2010-08-24 17:28)