Sha256: 8069ae5bec7fefcc347006202c24f02b6de1a816d02f50cf1ce4170982cb95dc

Contents?: true

Size: 1.71 KB

Versions: 4

Compression:

Stored size: 1.71 KB

Contents

module DynamicController
  class Responder

    def initialize(controller)
      @controller = controller
    end

    def index
      action :index,
             html: Proc.new {},
             json: Proc.new { render json: collection }
    end

    def show
      action :show,
             html: Proc.new {},
             json: Proc.new { render json: model }
    end

    def new
      action :new,
             html: Proc.new {}
    end

    def edit
      action :edit,
             html: Proc.new {}
    end

    def create
      action :create,
             html: Proc.new { redirect_to action: :show, id: model.id },
             json: Proc.new { render json: model, status: :created }
    end

    def update
      action :update,
             html: Proc.new { redirect_to action: :show, id: model.id },
             json: Proc.new { head :no_content }
    end

    def destroy
      action :destroy,
             html: Proc.new { redirect_to action: :index },
             json: Proc.new { head :no_content }
    end

    private

    def action(name, blocks={})
      @controller.instance_eval do
        if self.class.redefined_responder_to?(name)
          respond_to do |format|
            self.instance_exec format, &self.class.redefined_responder_to(name)
          end
        else
          respond_to do |format|
            self.class.responder_formats.each do |mime|
              if self.class.redefined_responder_to?(name, mime)
                format.send(mime) { self.instance_eval &self.class.redefined_responder_to(name, mime) }
              elsif blocks[mime]
                format.send(mime) { self.instance_eval &blocks[mime] }
              end
            end
          end
        end
      end
    end

  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
dynamic_controller-0.0.12 lib/dynamic_controller/responder.rb
dynamic_controller-0.0.11 lib/dynamic_controller/responder.rb
dynamic_controller-0.0.10 lib/dynamic_controller/responder.rb
dynamic_controller-0.0.9 lib/dynamic_controller/responder.rb