class Rack::WebProfiler::View
Public Class Methods
Initialize a new view.
@param template [String] template file path or content @option layout [String, nil] layout file path or content @option context [Rack::WebProfiler::View::Context, nil]
# File lib/rack/web_profiler/view.rb, line 13 def initialize(template, layout: nil, context: nil) @template = template @layout = layout @context = context @erb_options = { safe_level: nil, trim_mode: "<>-", eoutvar: "@_erbout", } end
Public Instance Methods
Get the context.
@return [Rack::WebProfiler::View::Context]
# File lib/rack/web_profiler/view.rb, line 44 def context @context ||= Context.new end
Get the result of view rendering.
@param variables [Hash, Binding] view variables
@return [String]
# File lib/rack/web_profiler/view.rb, line 30 def result(variables = {}) unless @template.nil? templates = [read_template(@template)] templates << read_template(@layout) unless @layout.nil? templates.inject(nil) do |prev, temp| render(temp, variables) { prev } end end end
Protected Instance Methods
Returns a [Hash] from a [Binding].
@param v [Binding]
@return [Hash]
# File lib/rack/web_profiler/view.rb, line 104 def binding_to_hash(v) h = {} v.eval("instance_variables").each do |k| h[k.to_s.sub(/^@/, "")] = v.eval("instance_variable_get(:#{k})") end h end
Format variables to inject them into view context.
@param v [Hash, Binding] variables
@return [Hash]
# File lib/rack/web_profiler/view.rb, line 88 def format_variables(v) case v when Binding binding_to_hash(v) when Hash v else {} end end
Read a template. Returns file content if template is a file path.
@param template [String] template file path or content
@return [String]
# File lib/rack/web_profiler/view.rb, line 55 def read_template(template) unless template.empty? path = ::File.expand_path("../../templates/#{template}", __FILE__) return ::File.read(path) if ::File.exist?(path) end template end
Render view.
@param str [String] view content @param variables [Hash, Binding] view variables
@return [String]
@todo better error when there is an ERB error.
# File lib/rack/web_profiler/view.rb, line 71 def render(str, variables = {}) format_variables(variables).each do |name, value| context.instance_variable_set("@#{name}", value) end erb = ::ERB.new(str, *@erb_options.values_at(:safe_level, :trim_mode, :eoutvar)) context.instance_eval do erb.result(binding).sub(/\A\n/, "") end end