2018-12-05 23:21:45 +05:30
# frozen_string_literal: true
2017-08-17 22:00:37 +05:30
module RoutableActions
extend ActiveSupport :: Concern
2021-11-11 11:23:49 +05:30
def find_routable! ( routable_klass , routable_full_path , full_path , extra_authorization_proc : nil )
2021-09-30 23:02:18 +05:30
routable = routable_klass . find_by_full_path ( routable_full_path , follow_redirects : request . get? )
2017-08-17 22:00:37 +05:30
if routable_authorized? ( routable , extra_authorization_proc )
2021-09-30 23:02:18 +05:30
ensure_canonical_path ( routable , routable_full_path )
2017-08-17 22:00:37 +05:30
routable
else
2021-11-11 11:23:49 +05:30
perform_not_found_actions ( routable , not_found_actions , full_path )
2018-12-13 13:39:08 +05:30
route_not_found unless performed?
2017-08-17 22:00:37 +05:30
nil
end
end
2019-09-04 21:01:54 +05:30
def not_found_actions
[ ProjectUnauthorized :: ControllerActions . on_routable_not_found ]
end
2021-11-11 11:23:49 +05:30
def perform_not_found_actions ( routable , actions , full_path )
2019-09-04 21:01:54 +05:30
actions . each do | action |
break if performed?
2021-11-11 11:23:49 +05:30
instance_exec ( routable , full_path , & action )
2019-09-04 21:01:54 +05:30
end
end
2017-08-17 22:00:37 +05:30
def routable_authorized? ( routable , extra_authorization_proc )
2018-12-13 13:39:08 +05:30
return false unless routable
2017-08-17 22:00:37 +05:30
action = :" read_ #{ routable . class . to_s . underscore } "
return false unless can? ( current_user , action , routable )
if extra_authorization_proc
extra_authorization_proc . call ( routable )
else
true
end
end
2021-09-30 23:02:18 +05:30
def ensure_canonical_path ( routable , routable_full_path )
2017-08-17 22:00:37 +05:30
return unless request . get?
canonical_path = routable . full_path
2021-09-30 23:02:18 +05:30
if canonical_path != routable_full_path
if ! request . xhr? && request . format . html? && canonical_path . casecmp ( routable_full_path ) != 0
flash [ :notice ] = " #{ routable . class . to_s . titleize } ' #{ routable_full_path } ' was moved to ' #{ canonical_path } '. Please update any links and bookmarks that may still have the old path. "
2017-08-17 22:00:37 +05:30
end
2018-03-17 18:26:18 +05:30
2021-01-29 00:20:46 +05:30
redirect_to build_canonical_path ( routable ) , status : :moved_permanently
2017-08-17 22:00:37 +05:30
end
end
end
2019-12-04 20:38:33 +05:30
2021-06-08 01:23:25 +05:30
RoutableActions . prepend_mod_with ( 'RoutableActions' )