Skip to content

Instantly share code, notes, and snippets.

@apeiros
Created March 19, 2012 14:13
Show Gist options
  • Save apeiros/2113723 to your computer and use it in GitHub Desktop.
Save apeiros/2113723 to your computer and use it in GitHub Desktop.
Controller-less rails template
class Remplate < AbstractController::Base
include AbstractController::Rendering
include AbstractController::Layouts
include AbstractController::Helpers
include AbstractController::Translation
include AbstractController::AssetPaths
include Rails.application.routes.url_helpers
self.view_paths = "app/views" # TODO: get it from Rails.application if available
# TODO: de-uglify
def self.prefixes_for_directory(path)
directories = []
dir = path
begin
directories << dir
dir = File.dirname(dir)
end until dir == "." unless dir == "."
directories
end
# TODO: verify that that's the mechanism used by rails
def self.prefixes_for_controller(controller)
controller.ancestors.grep(ApplicationController.singleton_class).map(&:controller_path)
end
# Render a controller action without instanciating the controller
# @example
# Remplate.view(Admin::UsersController, 'index').render users: User.all
def self.view(controller, action, params=nil, options=nil)
options = options ? options.dup : {}
options[:prefixes] ||= prefixes_for_controller(controller)
options[:template] = action
new(options)
end
# Render a template from string, similar to `render string: "template"`
# @example
# Remplate.string("%h1 Welcome \#{name}").render name: "Luser"
#
# TODO: dysfunctional
def self.string(string, options={})
new(options.merge(string: string))
end
# Render a file template, using its path to determine where partials are
# @example
# Remplate.file('users/index.html.haml').render users: User.all
def self.file(path, options={})
dir, file = File.split(path)
new(options.merge(template: path, prefixes: ['', *prefixes_for_directory(dir)]))
end
def initialize(options={})
@options = options
@_prefixes = @options[:prefixes] || [] # TODO: for some reason it's not picked up from the options, figure out why
super()
end
# @return [Remplate] a new Remplate instance with the additional options applied
def with(options)
self.class.new(@options.merge(options))
end
def render(locals={})
options = @options.merge(locals: locals)
super(options)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment