Skip to content
This repository has been archived by the owner on Dec 12, 2021. It is now read-only.

Commit

Permalink
Some refactor to be more DRY
Browse files Browse the repository at this point in the history
  • Loading branch information
Rafael Silva authored and ryanb committed Nov 26, 2009
1 parent c40490d commit e92a7d8
Showing 1 changed file with 21 additions and 10 deletions.
31 changes: 21 additions & 10 deletions lib/cancan/controller_additions.rb
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -83,14 +83,7 @@ def cannot?(*args)
# before_filter :load_resource # before_filter :load_resource
# #
def load_resource # TODO this could use some refactoring def load_resource # TODO this could use some refactoring
model_name = params[:controller].split('/').last.singularize self.model_instance = params[:id] ? model_class.find(params[:id]) : model_class.new(params[model_name.to_sym]) unless params[:action] == "index"
unless params[:action] == "index"
if params[:id]
instance_variable_set("@#{model_name}", model_name.camelcase.constantize.find(params[:id]))
else
instance_variable_set("@#{model_name}", model_name.camelcase.constantize.new(params[model_name.to_sym]))
end
end
end end


# Authorizes the resource in the current instance variable. For example, # Authorizes the resource in the current instance variable. For example,
Expand All @@ -106,8 +99,7 @@ def load_resource # TODO this could use some refactoring
# #
# See load_and_authorize_resource to automatically load the resource too. # See load_and_authorize_resource to automatically load the resource too.
def authorize_resource # TODO this could use some refactoring def authorize_resource # TODO this could use some refactoring
model_name = params[:controller].split('/').last.singularize unauthorized! if cannot?(params[:action].to_sym, model_instance || model_class)
unauthorized! if cannot?(params[:action].to_sym, instance_variable_get("@#{model_name}") || model_name.camelcase.constantize)
end end


# Calls load_resource to load the current resource model into an instance variable. # Calls load_resource to load the current resource model into an instance variable.
Expand All @@ -120,6 +112,25 @@ def load_and_authorize_resource
load_resource load_resource
authorize_resource authorize_resource
end end

private

def model_name
params[:controller].split('/').last.singularize
end

def model_class
model_name.camelcase.constantize
end

def model_instance
instance_variable_get("@#{model_name}")
end

def model_instance=(instance)
instance_variable_set("@#{model_name}", instance)
end

end end
end end


Expand Down

0 comments on commit e92a7d8

Please sign in to comment.