2018-09-14 01:42:05 -04:00
# frozen_string_literal: true
2017-05-01 16:46:30 -04:00
module RoutableActions
extend ActiveSupport :: Concern
2021-08-19 11:10:29 -04:00
def find_routable! ( routable_klass , routable_full_path , full_path , extra_authorization_proc : nil )
2021-07-27 14:10:54 -04:00
routable = routable_klass . find_by_full_path ( routable_full_path , follow_redirects : request . get? )
2017-05-11 16:57:03 -04:00
if routable_authorized? ( routable , extra_authorization_proc )
2021-07-27 14:10:54 -04:00
ensure_canonical_path ( routable , routable_full_path )
2017-05-04 17:20:13 -04:00
routable
else
2021-08-19 11:10:29 -04:00
perform_not_found_actions ( routable , not_found_actions , full_path )
2018-10-31 06:31:24 -04:00
route_not_found unless performed?
2017-05-04 17:20:13 -04:00
nil
end
end
2019-05-13 04:50:23 -04:00
def not_found_actions
[ ProjectUnauthorized :: ControllerActions . on_routable_not_found ]
end
2021-08-19 11:10:29 -04:00
def perform_not_found_actions ( routable , actions , full_path )
2019-05-13 04:50:23 -04:00
actions . each do | action |
2019-05-10 09:49:16 -04:00
break if performed?
2021-08-19 11:10:29 -04:00
instance_exec ( routable , full_path , & action )
2019-05-10 09:49:16 -04:00
end
end
2017-05-11 16:57:03 -04:00
def routable_authorized? ( routable , extra_authorization_proc )
2018-10-31 06:31:24 -04:00
return false unless routable
2017-05-11 16:57:03 -04:00
action = :" read_ #{ routable . class . to_s . underscore } "
2017-05-04 17:20:13 -04:00
return false unless can? ( current_user , action , routable )
2017-05-04 20:06:01 -04:00
if extra_authorization_proc
extra_authorization_proc . call ( routable )
2017-05-04 17:20:13 -04:00
else
true
end
end
2021-07-27 14:10:54 -04:00
def ensure_canonical_path ( routable , routable_full_path )
2017-05-01 16:46:30 -04:00
return unless request . get?
2017-05-04 20:06:01 -04:00
canonical_path = routable . full_path
2021-07-27 14:10:54 -04:00
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-05-04 20:06:01 -04:00
end
2018-01-11 11:34:01 -05:00
2020-10-23 14:08:31 -04:00
redirect_to build_canonical_path ( routable ) , status : :moved_permanently
2017-05-01 16:46:30 -04:00
end
end
end
2019-09-13 09:26:31 -04:00
2021-05-11 17:10:21 -04:00
RoutableActions . prepend_mod_with ( 'RoutableActions' )