Module: ResourcefulController::ClassMethods

Defined in:
lib/simply_authorized/resourceful_controller.rb

Instance Method Summary collapse

Instance Method Details

#resourceful(*args) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/simply_authorized/resourceful_controller.rb', line 6

def resourceful(*args)
  options = args.extract_options!
  resource = ActiveSupport::ModelName.new( options[:resource] ||
    self.model_name.split('::').last.gsub(/Controller$/,'').singularize)
#     resource = options[:resource] || ActiveSupport::ModelName.new(
#       self.model_name.split('::').last.gsub(/Controller$/,'').singularize)

  permissive

  before_filter :valid_id_required, 
    :only => [:show,:edit,:update,:destroy]

  #  by using before filters, the user
  #  can still add stuff to the action.
  before_filter :get_all, :only => :index
  before_filter :get_new, :only => :new

  define_method :destroy do
    instance_variable_get("@#{resource.singular}").send(:destroy)
    redirect_to send("#{resource.plural}_path")
  end

  define_method :create do
  begin
    instance_variable_set("@#{resource.singular}",
      resource.constantize.send(:new,params[resource.singular]))
    instance_variable_get("@#{resource.singular}").send(:save!)
    flash[:notice] = 'Success!'
    redirect_to instance_variable_get("@#{resource.singular}")
  rescue ActiveRecord::RecordNotSaved, ActiveRecord::RecordInvalid
    flash.now[:error] = "There was a problem creating " <<
      "the #{resource.singular}"
    render :action => "new"
  end
  end 

  define_method :update do
  begin
    instance_variable_get("@#{resource.singular}").send(
      :update_attributes!,params[resource.singular])
    flash[:notice] = 'Success!'
    redirect_to send(options[:update_redirect]||
      "#{resource.plural}_path")
  rescue ActiveRecord::RecordNotSaved, ActiveRecord::RecordInvalid
    flash.now[:error] = "There was a problem updating " <<
      "the #{resource.singular}"
    render :action => "edit"
  end
  end

  define_method :get_all do
    instance_variable_set("@#{resource.plural}",
      resource.constantize.send(:all) )
  end
  protected :get_all

  define_method :get_new do
    instance_variable_set("@#{resource.singular}",
      resource.constantize.send(:new) )
  end
  protected :get_new

  define_method :valid_id_required do
    if( !params[:id].blank? && 
        resource.constantize.send(:exists?,params[:id]) )
      instance_variable_set("@#{resource.singular}",
        resource.constantize.send(:find,params[:id]) )
    else
      access_denied("Valid id required!",
        send("#{resource.plural}_path") )
    end
  end
  protected :valid_id_required
end