Module: Effective::CrudController::ClassMethods

Defined in:
app/controllers/concerns/effective/crud_controller.rb

Instance Method Summary collapse

Instance Method Details

#member_action(action) ⇒ Object

Add the following to your controller for a simple member action member_action :print



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
# File 'app/controllers/concerns/effective/crud_controller.rb', line 11

def member_action(action)
  define_method(action) do
    self.resource ||= resource_class.find(params[:id])

    EffectiveResources.authorized?(self, action, resource)

    if (request.post? || request.patch? || request.put?)
      raise "expected @#{resource_name} to respond to #{action}!" unless resource.respond_to?("#{action}!")

      begin
        raise 'exception' unless resource.send("#{action}!")

        flash[:success] = "Successfully #{action}#{action.to_s.end_with?('e') ? 'd' : 'ed'} #{resource_human_name}"
        redirect_back fallback_location: resource_redirect_path
      rescue => e
        flash.now[:danger] = "Unable to #{action} #{resource_human_name}: #{resource.errors.full_messages.to_sentence.presence || e.message}"

        referer = request.referer.to_s

        if referer.end_with?(send(effective_resource.edit_path, resource))
          @page_title ||= "Edit #{resource}"
          render :edit
        elsif referer.end_with?(send(effective_resource.new_path))
          @page_title ||= "New #{resource_name.titleize}"
          render :new
        else
          @page_title ||= resource.to_s
          flash[:danger] = flash.now[:danger]

          if referer.present? && (Rails.application.routes.recognize_path(URI(referer).path) rescue false)
            redirect_back fallback_location: resource_redirect_path
          else
            redirect_to(resource_redirect_path)
          end
        end
      end
    end
  end
end