Sha256: 5f612ffa5e79933bafc2d2087e1e31f5dc4aadfb7d5aa5132bc24c9042681c98

Contents?: true

Size: 1.63 KB

Versions: 1

Compression:

Stored size: 1.63 KB

Contents

require "tilt/erb"

module Grimm
  class BaseController
    attr_reader :request, :response

    def initialize(request)
      @request = request
    end

    def params
      request.params
    end

    def render(*args)
      response(render_template(*args))
    end

    def response(body, status = 200, header = {})
      @response = Rack::Response.new(body, status, header)
    end

    def render_template(view_name, locals = {})
      template = Tilt::ERBTemplate.new(File.join( "app", "views",
                                       "layouts", "application.html.erb"))
      title = view_name.to_s.tr("_", " ").capitalize
      view = "#{view_name}.html.erb"
      view_template = Tilt::ERBTemplate.new(File.join( "app", "views",
                                                      controller_name, view))
      template.render(self, title: title) do
        view_template.render(self, locals.merge!(get_vars))
      end
    end

    def get_vars
      vars = {}
      instance_variables.each do |var|
        key = var.to_s.gsub("@","").to_sym
        vars[key] = instance_variable_get(var)
      end
      vars
    end

    def get_response
      @response
    end

    def controller_name
      self.class.to_s.gsub(/Controller$/, "").snake_case
    end

    def redirect_to(url)
        @response = Rack::Response.new(body = {}, status = 302, header = {"location" => url})
    end

    def dispatch(action)
      self.send(action)
      if get_response
        get_response
      else
        render(action)
        get_response
      end
    end

    def self.action(request, action_name)
       self.new(request).dispatch(action_name)
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
grimm-0.0.3 lib/grimm/controller.rb