A little background:
My app has tools
which have permission_levels
. There are User
's that have authorization for some tools
and not others. The admin panel is built using the rails_admin gem.
If the admin is editing a User
and that User
has access to tools
that the admin does not, these tools do not show up in the edit view (this is desired). However, when the admin updates the User
, the User
loses the associations to tools
and permission_levels
that were not shown.
To combat that, I overrode the #edit
action inside RailsAdmin. The resulting code is a bit of a mess, and I'd like to refactor by pulling out related code into methods, but the section is wrapped inside a Proc
.
How can I pull out the code below into methods? Specifically, the register_instance_option :controller
section.
.
.
.
module Actions
class Edit < RailsAdmin::Config::Actions::Base
register_instance_option :member? do
true
end
register_instance_option :route_fragment do
'edit'
end
register_instance_option :http_methods do
[:get, :put]
end
register_instance_option :visible? do
authorized?
end
register_instance_option :controller do
Proc.new do
if @object.class.base_class.name == 'User'
if request.get?
session[:tools] = (@object.tools - Tool.admined_by(current_user)).map(&:id)
pl = session[:tools].map do |t|
tl = Tool.find(t)
tl.permission_levels
end
session[:permission_levels] = []
pl.flatten.each do |p|
session[:permission_levels] << p if @object.permission_levels.include?(p)
end
session[:permission_levels].map!(&:id)
elsif request.put?
duped_tools = session[:tools].dup
params[:user][:tool_ids] = duped_tools.
concat(params[:user][:tool_ids]).uniq!.delete_if { |id| id == "" }.
map { |id| id.to_i }
duped_permission_levels = session[:permission_levels].dup
params[:user][:permission_level_ids] = duped_permission_levels.
concat(params[:user][:permission_level_ids]).uniq!.delete_if { |id| id == "" }.
map { |id| id.to_i }
if @object.update_attributes(params.require(:user).permit!)
session[:tools] = nil
session[:permission_levels] = nil
duped_session = nil
flash[:success] = t("admin.flash.successful", :name => @model_config.label, :action => t("admin.actions.edit.done"))
redirect_to index_path
else
flash[:error] = t("admin.flash.error", :name => @model_config.label, :action => t("admin.actions.edit.done"))
redirect_path = back_or_index
end
end
end
end
end
register_instance_option :link_icon do
'icon-pencil'
end
end
end
.
.
.