routable_actions.rb 1.21 KB
Newer Older
1 2 3
module RoutableActions
  extend ActiveSupport::Concern

Michael Kozono's avatar
Michael Kozono committed
4
  def find_routable!(routable_klass, requested_full_path, extra_authorization_proc: nil)
5 6
    routable = routable_klass.find_by_full_path(requested_full_path, follow_redirects: request.get?)

7
    if routable_authorized?(routable, extra_authorization_proc)
8 9 10 11 12 13 14 15
      ensure_canonical_path(routable, requested_full_path)
      routable
    else
      route_not_found
      nil
    end
  end

16 17
  def routable_authorized?(routable, extra_authorization_proc)
    action = :"read_#{routable.class.to_s.underscore}"
18 19
    return false unless can?(current_user, action, routable)

Michael Kozono's avatar
Michael Kozono committed
20 21
    if extra_authorization_proc
      extra_authorization_proc.call(routable)
22 23 24 25 26
    else
      true
    end
  end

27
  def ensure_canonical_path(routable, requested_full_path)
28 29
    return unless request.get?

Michael Kozono's avatar
Michael Kozono committed
30
    canonical_path = routable.full_path
31 32 33
    if canonical_path != requested_full_path
      if canonical_path.casecmp(requested_full_path) != 0
        flash[:notice] = "#{routable.class.to_s.titleize} '#{requested_full_path}' was moved to '#{canonical_path}'. Please update any links and bookmarks that may still have the old path."
Michael Kozono's avatar
Michael Kozono committed
34
      end
35
      redirect_to build_canonical_path(routable)
36 37 38
    end
  end
end