Module: Subdomainify::RouteSet

Defined in:
lib/subdomainify/route_set.rb

Overview

Private: Module for rewriting plain path into subdomain path.

Instance Method Summary collapse

Instance Method Details

#url_for_with_subdomain(options) ⇒ Object

Public: Rewrite normal route into route with subdomain if user links to or from subdomain enabled routes. In such situation, :only_path option will be ignored.



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/subdomainify/route_set.rb', line 9

def url_for_with_subdomain(options)
  options = default_url_options.merge(options || {})

  if needs_subdomain?(options)
    options[:only_path] = false

    # Use route with highest precedence value (i.e. shortest route).
    # TODO: Better ways to detect part name for nested resource?
    subroute = @set.select { |route| route.defaults[:subdomainify] }.last
    name = subroute.defaults[:controller].split('/').last.to_s.singularize
    name = subroute.name if subroute.name.present?
    subdomain_id = options[:"#{name}_id"] || options[:id]

    # On realm transfer, when user links from subdomain route to
    # bare route (i.e. :subdomainify is false) then we don't really
    # need subdomain to be present even if subdomain id is present.
    if options[:subdomainify] && subdomain_id
      options[:subdomain] = subdomain_id.to_param
    else
      default_options = ActionController::Base.default_url_options
      options[:subdomain] = default_options[:subdomain]
    end

    # Turn /blog/foo/articles/ to just /articles/ using subroute prefix.
    prefix = subroute.format(id: options[:subdomain])
    url = URI.parse(url_for_without_subdomain(options))
    url.path.gsub!(/^#{prefix}\/?/, '/')
    url.to_s
  else
    url_for_without_subdomain(options)
  end
end