Skip to content

Instantly share code, notes, and snippets.

@kristianmandrup
Created August 25, 2010 17:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kristianmandrup/549965 to your computer and use it in GitHub Desktop.
Save kristianmandrup/549965 to your computer and use it in GitHub Desktop.
Inline Rails 3 templating solution : for ActionView RSpec testing etc.
require 'action_view'
require 'action_view/context'
class TestERBTemplate
ERBHandler = ActionView::Template::Handlers::ERB
attr_accessor :output_buffer, :rendered
def initialize
@output_buffer = ActiveSupport::SafeBuffer.new
@rendered = ''
end
def render(options = {}, local_assigns = {}, &block)
view.assign(_assigns)
output = view.render(options, local_assigns, &block)
@rendered << output
output
end
module Locals
attr_accessor :locals
end
def locals
@locals ||= {}
end
def view
@view ||= begin
# lookup_context = nil, assigns_for_first_render = {}
view = ActionView::Base.new
# ???
# view.singleton_class.send :include, _helpers
view.extend(Locals)
view.locals = self.locals
view.output_buffer = self.output_buffer
view
end
end
alias_method :_view, :view
EXCLUDE_IVARS = %w{
@_assertion_wrapped
@_result
@controller
@layouts
@locals
@method_name
@output_buffer
@partials
@rendered
@request
@routes
@templates
@test_passed
@view
@view_context_class
}
def _instance_variables
instance_variables.map(&:to_s) - EXCLUDE_IVARS
end
def _assigns
_instance_variables.inject({}) do |hash, var|
name = var[1..-1].to_sym
hash[name] = instance_variable_get(var)
hash
end
end
def basic_template content
@body = content
# assert_equal "Hello", render
puts render :inline => content
# render(:my_local => "I'm a local")
end
end
module MyViewHelper
def tab_for(clazz, &block)
content = with_output_buffer(&block)
content_tag :li, content, :class => clazz
end
end
module MyOtherViewHelper
def hello(clazz, &block)
content = with_output_buffer(&block)
content_tag :div, content, :class => clazz
end
end
class ActionView::Base
include MyViewHelper, MyOtherViewHelper
def name
'Kristian'
end
end
test = TestERBTemplate.new # 'h'
test.basic_template "hello <%= name %>"
test.basic_template %{
<%= tab_for :x do %>
<%= hello :blip do %>
ged
<% end %>
<% end %>
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment