Sha256: b9072dd40bf1b28d2d5e013769a51c0d338cb9e5b6f4255df32aa0d3afeedc6b

Contents?: true

Size: 1.89 KB

Versions: 1

Compression:

Stored size: 1.89 KB

Contents

require 'cancan'

module Customs
  module ControlFlow

    # GET actions

    def index
      respond_with resource_collection
    end

    [:new, :show, :edit].each do |name|
      define_method name do
        respond_with resource
      end
    end

    # Other actions

    def create
      save_resource
      success_response
    end

    def update
      save_resource
      success_response
    end

    def destroy
      destroy_resource
      success_response
    end


  protected

    # Resource naming

    def resource_name
      @resource_name ||= resource_name_from_controller
    end

    def resource_name_from_controller
      params[:controller].sub("Controller", "").underscore.split('/').last.singularize
    end

    def resource_class
      @resource_class ||= resource_name.to_s.classify.constantize
    end

    def resource_params
      params[resource_name]
    end

    # Resources

    def resource_collection
      instance_variable_get "@#{resource_name.to_s.pluralize}"
    end

    def resource
      instance_variable_get "@#{resource_name.to_s}"
    end

    # Resource actions

    def save_resource
      resource.assign_attributes resource_params

      args = [:save]
      args << action_name unless ::Rails.version.to_f >= 4.0

      run_callbacks *args do
        resource.save!
      end
    end

    def destroy_resource
      args = [:destroy]
      args << action_name unless ::Rails.version.to_f >= 4.0

      run_callbacks *args do
        if resource.respond_to? :destroy!
          resource.destroy!
        else
          resource.destroy
        end
      end
    end

    # Response

    def success_response
      respond_with resource, :location => resource_location
    end

    def resource_location
      case action_name
      when 'create'  then resource
      when 'update'  then resource
      when 'destroy' then resource_name.to_s.pluralize.to_sym
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
customs-1.1.0 lib/customs/control_flow.rb