class Locomotive::Steam::Middlewares::Site

Fetch a site using the site_finder service. Look for an existing site in the rack env variable (context: when launched from the Engine).

Public Instance Methods

_call() click to toggle source
# File lib/locomotive/steam/middlewares/site.rb, line 11
def _call
  site = find_site

  no_site! if site.nil?

  # log anyway
  log_site(site)

  # redirect to the first domain and/or HTTPS if defined by the site
  redirect_if_required(site)
end

Private Instance Methods

find_site() click to toggle source
# File lib/locomotive/steam/middlewares/site.rb, line 25
def find_site
  if env['steam.site']
    # happens if Steam is running within the Engine
    services.set_site(env['steam.site'])
  else
    env['steam.site'] = services.current_site
  end
end
log_site(site) click to toggle source
# File lib/locomotive/steam/middlewares/site.rb, line 69
def log_site(site)
  if site.nil?
    msg = "Unable to find a site, url asked: #{request.url} ".colorize(color: :light_white, background: :red)
  else
    msg = site.name.colorize(color: :light_white, background: :blue)
  end

  log msg, 0
end
no_site!() click to toggle source
# File lib/locomotive/steam/middlewares/site.rb, line 34
def no_site!
  # render a simple message if the service was not able to find a site
  # based on the request.
  if services.configuration.render_404_if_no_site
    render_response('Hi, we are sorry but no site was found.', 404, 'text/html')
  else
    raise NoSiteException.new
  end
end
redirect_if_required(site) click to toggle source
# File lib/locomotive/steam/middlewares/site.rb, line 44
def redirect_if_required(site)
  return if env['steam.is_default_host']

  if redirect_to_first_domain?(site) || redirect_to_https?(site)
    klass = request.scheme == 'https' || redirect_to_https?(site) ? URI::HTTPS : URI::HTTP
    redirect_to klass.build(
      host:   site.domains.first,
      port:   [80, 443].include?(request.port) ? nil : request.port,
      path:   request.path,
      query:  request.query_string.present? ? request.query_string : nil).to_s
  end
end
redirect_to_first_domain?(site) click to toggle source
# File lib/locomotive/steam/middlewares/site.rb, line 57
def redirect_to_first_domain?(site)
  # the site parameter can be an instance of Locomotive::Steam::Services::Defer and
  # so comparing just site may not be reliable.
  site.try(:redirect_to_first_domain) &&
  site.domains.first != request.host
end
redirect_to_https?(site) click to toggle source
# File lib/locomotive/steam/middlewares/site.rb, line 64
def redirect_to_https?(site)
  site.try(:redirect_to_https) &&
  request.scheme != 'https'
end