Sha256: 2ae73b7f0487175e3b3a5f7ca88ecef68ccec4f17e14412d006e8e3a6e0c8073

Contents?: true

Size: 1.62 KB

Versions: 1

Compression:

Stored size: 1.62 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($:.first, "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($:.first, "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.delete("@").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({}, 302, "location" => url)
    end

    def dispatch(action)
      send(action)
      render(action) unless get_response
      get_response
    end

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

Version data entries

1 entries across 1 versions & 1 rubygems

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