PageRenderTime 85ms CodeModel.GetById 31ms RepoModel.GetById 0ms app.codeStats 0ms

/actionview/lib/action_view/template.rb

https://github.com/atambo/rails
Ruby | 340 lines | 151 code | 36 blank | 153 comment | 18 complexity | a7ea2441a378637a091601ad82d0be9f MD5 | raw file
  1. require 'active_support/core_ext/object/try'
  2. require 'active_support/core_ext/kernel/singleton_class'
  3. require 'thread'
  4. module ActionView
  5. # = Action View Template
  6. class Template
  7. extend ActiveSupport::Autoload
  8. # === Encodings in ActionView::Template
  9. #
  10. # ActionView::Template is one of a few sources of potential
  11. # encoding issues in Rails. This is because the source for
  12. # templates are usually read from disk, and Ruby (like most
  13. # encoding-aware programming languages) assumes that the
  14. # String retrieved through File IO is encoded in the
  15. # <tt>default_external</tt> encoding. In Rails, the default
  16. # <tt>default_external</tt> encoding is UTF-8.
  17. #
  18. # As a result, if a user saves their template as ISO-8859-1
  19. # (for instance, using a non-Unicode-aware text editor),
  20. # and uses characters outside of the ASCII range, their
  21. # users will see diamonds with question marks in them in
  22. # the browser.
  23. #
  24. # For the rest of this documentation, when we say "UTF-8",
  25. # we mean "UTF-8 or whatever the default_internal encoding
  26. # is set to". By default, it will be UTF-8.
  27. #
  28. # To mitigate this problem, we use a few strategies:
  29. # 1. If the source is not valid UTF-8, we raise an exception
  30. # when the template is compiled to alert the user
  31. # to the problem.
  32. # 2. The user can specify the encoding using Ruby-style
  33. # encoding comments in any template engine. If such
  34. # a comment is supplied, Rails will apply that encoding
  35. # to the resulting compiled source returned by the
  36. # template handler.
  37. # 3. In all cases, we transcode the resulting String to
  38. # the UTF-8.
  39. #
  40. # This means that other parts of Rails can always assume
  41. # that templates are encoded in UTF-8, even if the original
  42. # source of the template was not UTF-8.
  43. #
  44. # From a user's perspective, the easiest thing to do is
  45. # to save your templates as UTF-8. If you do this, you
  46. # do not need to do anything else for things to "just work".
  47. #
  48. # === Instructions for template handlers
  49. #
  50. # The easiest thing for you to do is to simply ignore
  51. # encodings. Rails will hand you the template source
  52. # as the default_internal (generally UTF-8), raising
  53. # an exception for the user before sending the template
  54. # to you if it could not determine the original encoding.
  55. #
  56. # For the greatest simplicity, you can support only
  57. # UTF-8 as the <tt>default_internal</tt>. This means
  58. # that from the perspective of your handler, the
  59. # entire pipeline is just UTF-8.
  60. #
  61. # === Advanced: Handlers with alternate metadata sources
  62. #
  63. # If you want to provide an alternate mechanism for
  64. # specifying encodings (like ERB does via <%# encoding: ... %>),
  65. # you may indicate that you will handle encodings yourself
  66. # by implementing <tt>self.handles_encoding?</tt>
  67. # on your handler.
  68. #
  69. # If you do, Rails will not try to encode the String
  70. # into the default_internal, passing you the unaltered
  71. # bytes tagged with the assumed encoding (from
  72. # default_external).
  73. #
  74. # In this case, make sure you return a String from
  75. # your handler encoded in the default_internal. Since
  76. # you are handling out-of-band metadata, you are
  77. # also responsible for alerting the user to any
  78. # problems with converting the user's data to
  79. # the <tt>default_internal</tt>.
  80. #
  81. # To do so, simply raise +WrongEncodingError+ as follows:
  82. #
  83. # raise WrongEncodingError.new(
  84. # problematic_string,
  85. # expected_encoding
  86. # )
  87. eager_autoload do
  88. autoload :Error
  89. autoload :Handlers
  90. autoload :Text
  91. autoload :Types
  92. end
  93. extend Template::Handlers
  94. attr_accessor :locals, :formats, :virtual_path
  95. attr_reader :source, :identifier, :handler, :original_encoding, :updated_at
  96. # This finalizer is needed (and exactly with a proc inside another proc)
  97. # otherwise templates leak in development.
  98. Finalizer = proc do |method_name, mod|
  99. proc do
  100. mod.module_eval do
  101. remove_possible_method method_name
  102. end
  103. end
  104. end
  105. def initialize(source, identifier, handler, details)
  106. format = details[:format] || (handler.default_format if handler.respond_to?(:default_format))
  107. @source = source
  108. @identifier = identifier
  109. @handler = handler
  110. @compiled = false
  111. @original_encoding = nil
  112. @locals = details[:locals] || []
  113. @virtual_path = details[:virtual_path]
  114. @updated_at = details[:updated_at] || Time.now
  115. @formats = Array(format).map { |f| f.respond_to?(:ref) ? f.ref : f }
  116. @compile_mutex = Mutex.new
  117. end
  118. # Returns if the underlying handler supports streaming. If so,
  119. # a streaming buffer *may* be passed when it start rendering.
  120. def supports_streaming?
  121. handler.respond_to?(:supports_streaming?) && handler.supports_streaming?
  122. end
  123. # Render a template. If the template was not compiled yet, it is done
  124. # exactly before rendering.
  125. #
  126. # This method is instrumented as "!render_template.action_view". Notice that
  127. # we use a bang in this instrumentation because you don't want to
  128. # consume this in production. This is only slow if it's being listened to.
  129. def render(view, locals, buffer=nil, &block)
  130. instrument("!render_template") do
  131. compile!(view)
  132. view.send(method_name, locals, buffer, &block)
  133. end
  134. rescue Exception => e
  135. handle_render_error(view, e)
  136. end
  137. def type
  138. @type ||= Types[@formats.first] if @formats.first
  139. end
  140. # Receives a view object and return a template similar to self by using @virtual_path.
  141. #
  142. # This method is useful if you have a template object but it does not contain its source
  143. # anymore since it was already compiled. In such cases, all you need to do is to call
  144. # refresh passing in the view object.
  145. #
  146. # Notice this method raises an error if the template to be refreshed does not have a
  147. # virtual path set (true just for inline templates).
  148. def refresh(view)
  149. raise "A template needs to have a virtual path in order to be refreshed" unless @virtual_path
  150. lookup = view.lookup_context
  151. pieces = @virtual_path.split("/")
  152. name = pieces.pop
  153. partial = !!name.sub!(/^_/, "")
  154. lookup.disable_cache do
  155. lookup.find_template(name, [ pieces.join('/') ], partial, @locals)
  156. end
  157. end
  158. def inspect
  159. @inspect ||= defined?(Rails.root) ? identifier.sub("#{Rails.root}/", '') : identifier
  160. end
  161. # This method is responsible for properly setting the encoding of the
  162. # source. Until this point, we assume that the source is BINARY data.
  163. # If no additional information is supplied, we assume the encoding is
  164. # the same as <tt>Encoding.default_external</tt>.
  165. #
  166. # The user can also specify the encoding via a comment on the first
  167. # line of the template (# encoding: NAME-OF-ENCODING). This will work
  168. # with any template engine, as we process out the encoding comment
  169. # before passing the source on to the template engine, leaving a
  170. # blank line in its stead.
  171. def encode!
  172. return unless source.encoding == Encoding::BINARY
  173. # Look for # encoding: *. If we find one, we'll encode the
  174. # String in that encoding, otherwise, we'll use the
  175. # default external encoding.
  176. if source.sub!(/\A#{ENCODING_FLAG}/, '')
  177. encoding = magic_encoding = $1
  178. else
  179. encoding = Encoding.default_external
  180. end
  181. # Tag the source with the default external encoding
  182. # or the encoding specified in the file
  183. source.force_encoding(encoding)
  184. # If the user didn't specify an encoding, and the handler
  185. # handles encodings, we simply pass the String as is to
  186. # the handler (with the default_external tag)
  187. if !magic_encoding && @handler.respond_to?(:handles_encoding?) && @handler.handles_encoding?
  188. source
  189. # Otherwise, if the String is valid in the encoding,
  190. # encode immediately to default_internal. This means
  191. # that if a handler doesn't handle encodings, it will
  192. # always get Strings in the default_internal
  193. elsif source.valid_encoding?
  194. source.encode!
  195. # Otherwise, since the String is invalid in the encoding
  196. # specified, raise an exception
  197. else
  198. raise WrongEncodingError.new(source, encoding)
  199. end
  200. end
  201. protected
  202. # Compile a template. This method ensures a template is compiled
  203. # just once and removes the source after it is compiled.
  204. def compile!(view) #:nodoc:
  205. return if @compiled
  206. # Templates can be used concurrently in threaded environments
  207. # so compilation and any instance variable modification must
  208. # be synchronized
  209. @compile_mutex.synchronize do
  210. # Any thread holding this lock will be compiling the template needed
  211. # by the threads waiting. So re-check the @compiled flag to avoid
  212. # re-compilation
  213. return if @compiled
  214. if view.is_a?(ActionView::CompiledTemplates)
  215. mod = ActionView::CompiledTemplates
  216. else
  217. mod = view.singleton_class
  218. end
  219. instrument("!compile_template") do
  220. compile(view, mod)
  221. end
  222. # Just discard the source if we have a virtual path. This
  223. # means we can get the template back.
  224. @source = nil if @virtual_path
  225. @compiled = true
  226. end
  227. end
  228. # Among other things, this method is responsible for properly setting
  229. # the encoding of the compiled template.
  230. #
  231. # If the template engine handles encodings, we send the encoded
  232. # String to the engine without further processing. This allows
  233. # the template engine to support additional mechanisms for
  234. # specifying the encoding. For instance, ERB supports <%# encoding: %>
  235. #
  236. # Otherwise, after we figure out the correct encoding, we then
  237. # encode the source into <tt>Encoding.default_internal</tt>.
  238. # In general, this means that templates will be UTF-8 inside of Rails,
  239. # regardless of the original source encoding.
  240. def compile(view, mod) #:nodoc:
  241. encode!
  242. method_name = self.method_name
  243. code = @handler.call(self)
  244. # Make sure that the resulting String to be eval'd is in the
  245. # encoding of the code
  246. source = <<-end_src
  247. def #{method_name}(local_assigns, output_buffer)
  248. _old_virtual_path, @virtual_path = @virtual_path, #{@virtual_path.inspect};_old_output_buffer = @output_buffer;#{locals_code};#{code}
  249. ensure
  250. @virtual_path, @output_buffer = _old_virtual_path, _old_output_buffer
  251. end
  252. end_src
  253. # Make sure the source is in the encoding of the returned code
  254. source.force_encoding(code.encoding)
  255. # In case we get back a String from a handler that is not in
  256. # BINARY or the default_internal, encode it to the default_internal
  257. source.encode!
  258. # Now, validate that the source we got back from the template
  259. # handler is valid in the default_internal. This is for handlers
  260. # that handle encoding but screw up
  261. unless source.valid_encoding?
  262. raise WrongEncodingError.new(@source, Encoding.default_internal)
  263. end
  264. begin
  265. mod.module_eval(source, identifier, 0)
  266. ObjectSpace.define_finalizer(self, Finalizer[method_name, mod])
  267. rescue Exception => e # errors from template code
  268. if logger = (view && view.logger)
  269. logger.debug "ERROR: compiling #{method_name} RAISED #{e}"
  270. logger.debug "Function body: #{source}"
  271. logger.debug "Backtrace: #{e.backtrace.join("\n")}"
  272. end
  273. raise ActionView::Template::Error.new(self, e)
  274. end
  275. end
  276. def handle_render_error(view, e) #:nodoc:
  277. if e.is_a?(Template::Error)
  278. e.sub_template_of(self)
  279. raise e
  280. else
  281. template = self
  282. unless template.source
  283. template = refresh(view)
  284. template.encode!
  285. end
  286. raise Template::Error.new(template, e)
  287. end
  288. end
  289. def locals_code #:nodoc:
  290. # Double assign to suppress the dreaded 'assigned but unused variable' warning
  291. @locals.map { |key| "#{key} = #{key} = local_assigns[:#{key}];" }.join
  292. end
  293. def method_name #:nodoc:
  294. @method_name ||= "_#{identifier_method_name}__#{@identifier.hash}_#{__id__}".gsub('-', "_")
  295. end
  296. def identifier_method_name #:nodoc:
  297. inspect.gsub(/[^a-z_]/, '_')
  298. end
  299. def instrument(action, &block)
  300. payload = { virtual_path: @virtual_path, identifier: @identifier }
  301. ActiveSupport::Notifications.instrument("#{action}.action_view", payload, &block)
  302. end
  303. end
  304. end