pax_global_header00006660000000000000000000000064135222660050014513gustar00rootroot0000000000000052 comment=9be4e1fd86a5086ba234053f5c21eeece39af681 haml-5.1.2/000077500000000000000000000000001352226600500124415ustar00rootroot00000000000000haml-5.1.2/.gitignore000066400000000000000000000002461352226600500144330ustar00rootroot00000000000000/.yardoc /coverage /doc /log /pkg /test/rails /test/gemfiles/*.lock /.haml /site *.rbc .sass-cache .rbenv-version .rbx .ruby-version .rvmrc Gemfile.lock tmp .bundle/ haml-5.1.2/.gitmodules000066400000000000000000000001371352226600500146170ustar00rootroot00000000000000[submodule "test/haml-spec"] path = test/haml-spec url = git://github.com/haml/haml-spec.git haml-5.1.2/.travis.yml000066400000000000000000000056151352226600500145610ustar00rootroot00000000000000sudo: false dist: trusty language: ruby cache: bundler rvm: - ruby-head - 2.6.3 - 2.5.5 - 2.4.6 - 2.3.8 - 2.2.10 - 2.1.10 - 2.0.0 - jruby-9.2.7.0 - rbx-3 gemfile: - test/gemfiles/Gemfile.rails-6.0.x - test/gemfiles/Gemfile.rails-5.2.x - test/gemfiles/Gemfile.rails-5.1.x - test/gemfiles/Gemfile.rails-5.0.x - test/gemfiles/Gemfile.rails-5.0.x.erubi - test/gemfiles/Gemfile.rails-4.2.x - test/gemfiles/Gemfile.rails-4.1.x - test/gemfiles/Gemfile.rails-4.0.x matrix: exclude: - rvm: 2.0.0 gemfile: test/gemfiles/Gemfile.rails-6.0.x - rvm: 2.1.10 gemfile: test/gemfiles/Gemfile.rails-6.0.x - rvm: 2.2.10 gemfile: test/gemfiles/Gemfile.rails-6.0.x - rvm: 2.3.8 gemfile: test/gemfiles/Gemfile.rails-6.0.x - rvm: 2.4.6 gemfile: test/gemfiles/Gemfile.rails-6.0.x - rvm: 2.0.0 gemfile: test/gemfiles/Gemfile.rails-5.2.x - rvm: 2.1.10 gemfile: test/gemfiles/Gemfile.rails-5.2.x - rvm: 2.0.0 gemfile: test/gemfiles/Gemfile.rails-5.1.x - rvm: 2.1.10 gemfile: test/gemfiles/Gemfile.rails-5.1.x - rvm: 2.0.0 gemfile: test/gemfiles/Gemfile.rails-5.0.x - rvm: 2.0.0 gemfile: test/gemfiles/Gemfile.rails-5.0.x.erubi - rvm: 2.1.10 gemfile: test/gemfiles/Gemfile.rails-5.0.x - rvm: 2.1.10 gemfile: test/gemfiles/Gemfile.rails-5.0.x.erubi - rvm: 2.4.6 gemfile: test/gemfiles/Gemfile.rails-4.0.x - rvm: 2.4.6 gemfile: test/gemfiles/Gemfile.rails-4.1.x - rvm: 2.4.6 gemfile: test/gemfiles/Gemfile.rails-4.2.x - rvm: 2.5.5 gemfile: test/gemfiles/Gemfile.rails-4.0.x - rvm: 2.5.5 gemfile: test/gemfiles/Gemfile.rails-4.1.x - rvm: 2.5.5 gemfile: test/gemfiles/Gemfile.rails-4.2.x - rvm: 2.6.3 gemfile: test/gemfiles/Gemfile.rails-4.0.x - rvm: 2.6.3 gemfile: test/gemfiles/Gemfile.rails-4.1.x - rvm: 2.6.3 gemfile: test/gemfiles/Gemfile.rails-4.2.x - rvm: ruby-head gemfile: test/gemfiles/Gemfile.rails-4.0.x - rvm: ruby-head gemfile: test/gemfiles/Gemfile.rails-4.1.x - rvm: ruby-head gemfile: test/gemfiles/Gemfile.rails-4.2.x include: - rvm: 2.6.3 gemfile: test/gemfiles/Gemfile.rails-edge allow_failures: - rvm: ruby-head - rvm: rbx-3 - gemfile: test/gemfiles/Gemfile.rails-edge - rvm: jruby-9.2.7.0 gemfile: test/gemfiles/Gemfile.rails-4.2.x - rvm: jruby-9.2.7.0 gemfile: test/gemfiles/Gemfile.rails-4.1.x - rvm: jruby-9.2.7.0 gemfile: test/gemfiles/Gemfile.rails-4.0.x - rvm: jruby-9.2.7.0 gemfile: test/gemfiles/Gemfile.rails-5.0.x.erubi fast_finish: true before_install: - gem i rubygems-update -v '<3' && update_rubygems # https://github.com/travis-ci/travis-ci/issues/8974 - gem uninstall -v '>= 2' -i $(rvm gemdir)@global -ax bundler || true - gem i bundler -v '<2' script: "bundle exec rake submodules test" haml-5.1.2/.yardopts000066400000000000000000000011451352226600500143100ustar00rootroot00000000000000--charset utf-8 --readme README.md --markup markdown --markup-provider kramdown --template-path yard --default-return "" --title "Haml Documentation" --query 'object.type != :classvariable' --query 'object.type != :constant || @api && @api.text == "public"' --exclude lib/haml/plugin.rb --exclude lib/haml/railtie.rb --exclude lib/haml/helpers/action_view_mods.rb --exclude lib/haml/helpers/xss_mods.rb --hide-void-return --protected --no-private --no-highlight - FAQ.md CHANGELOG.md REFERENCE.md MIT-LICENSE haml-5.1.2/CHANGELOG.md000066400000000000000000001441741352226600500142650ustar00rootroot00000000000000# Haml Changelog ## 5.1.2 Released on August 6, 2019 ([diff](https://github.com/haml/haml/compare/v5.1.1...v5.1.2)). * Fix crash in some environments such as New Relic by unfreezing string literals for ParseNode#inspect. [#1016](https://github.com/haml/haml/pull/1016) (thanks [Jalyna](https://github.com/jalyna)) ## 5.1.1 Released on May 25, 2019 ([diff](https://github.com/haml/haml/compare/v5.1.0...v5.1.1)). * Fix NameError bug that happens on ruby 2.6.1-2.6.3 + haml 5.1.0 + rails < 5.1 + erubi. (Akira Matsuda) ## 5.1.0 Released on May 16, 2019 ([diff](https://github.com/haml/haml/compare/v5.0.4...v5.1.0)). * Rails 6 support [#1008](https://github.com/haml/haml/pull/1008) (thanks [Seb Jacobs](https://github.com/sebjacobs)) * Add `escape_filter_interpolations` option for backwards compatibility with haml 4 defaults [#984](https://github.com/haml/haml/pull/984) (thanks [Will Jordan](https://github.com/wjordan)) * Fix error on empty :javascript and :css filter blocks [#986](https://github.com/haml/haml/pull/986) (thanks [Will Jordan](https://github.com/wjordan)) * Respect changes in Haml::Options.defaults in `Haml::TempleEngine` options (Takashi Kokubun) * Un-freeze TempleEngine precompiled string literals [#983](https://github.com/haml/haml/pull/983) (thanks [Will Jordan](https://github.com/wjordan)) * Various performance/memory improvements [#965](https://github.com/haml/haml/pull/965), [#966](https://github.com/haml/haml/pull/966), [#963](https://github.com/haml/haml/pull/963) (thanks [Dillon Welch](https://github.com/oniofchaos)) * Enable `frozen_string_literal` magic comment for all .rb files [#967](https://github.com/haml/haml/pull/967) (thanks [Dillon Welch](https://github.com/oniofchaos)) ## 5.0.4 Released on October 13, 2017 ([diff](https://github.com/haml/haml/compare/v5.0.3...v5.0.4)). * Fix `haml -c --stdin` regression in 5.0.2. [#958](https://github.com/haml/haml/pull/958) (thanks [Timo Göllner](https://github.com/TeaMoe)) * Ruby 2.5 support (it wasn't working due to Ripper API change). (Akira Matsuda) ## 5.0.3 Released on September 7, 2017 ([diff](https://github.com/haml/haml/compare/v5.0.2...v5.0.3)). * Use `String#dump` instead of `String#inspect` to generate string literal. (Takashi Kokubun) * Fix Erubi superclass mismatch error. [#952](https://github.com/haml/haml/pull/952) (thanks [Robin Daugherty](https://github.com/RobinDaugherty)) ## 5.0.2 Released on August 1, 2017 ([diff](https://github.com/haml/haml/compare/v5.0.1...v5.0.2)). * Let `haml -c` fail if generated Ruby code is syntax error. [#880](https://github.com/haml/haml/issues/880) (Takashi Kokubun) * Fix `NoMethodError` bug caused with Sprockets 3 and :sass filter. [#930](https://github.com/haml/haml/pull/930) (thanks [Gonzalez Maximiliano](https://github.com/emaxi)) * Fix `list_of` helper with multi-line content. [#933](https://github.com/haml/haml/pull/933) (thanks [Benoit Larroque](https://github.com/zetaben)) * Optimize rendering performance by changing timing to fix textareas. [#941](https://github.com/haml/haml/pull/941) (Takashi Kokubun) * Fix `TypeError` with empty :ruby filter. [#942](https://github.com/haml/haml/pull/942) (Takashi Kokubun) * Fix inconsistent attribute sort order. (Takashi Kokubun) ## 5.0.1 Released on May 3, 2017 ([diff](https://github.com/haml/haml/compare/v5.0.0...v5.0.1)). * Fix parsing attributes including string interpolation. [#917](https://github.com/haml/haml/pull/917) [#921](https://github.com/haml/haml/issues/921) * Stop distributing test files in gem package and allow installing on Windows. * Use ActionView's Erubi/Erubis handler for erb filter only on ActionView. [#914](https://github.com/haml/haml/pull/914) ## 5.0.0 Released on April 26, 2017 ([diff](https://github.com/haml/haml/compare/4.0.7...v5.0.0)). Breaking Changes * Haml now requires Ruby 2.0.0 or above. * Rails 3 is no longer supported, matching the official [Maintenance Policy for Ruby on Rails](http://weblog.rubyonrails.org/2013/2/24/maintenance-policy-for-ruby-on-rails/). Use Haml 4 if you want to use Rails 3. (Tee Parham) * Remove `:ugly` option ([#894](https://github.com/haml/haml/pull/894)) * The `haml` command's debug option (`-d`) no longer executes the Haml code, but rather checks the generated Ruby syntax for errors. * Drop parser/compiler accessor from `Haml::Engine`. Modify `Haml::Engine#initialize` options or `Haml::Template.options` instead. (Takashi Kokubun) * Drop dynamic quotes support and always escape `'` for `escape_html`/`escape_attrs` instead. Also, escaped results are slightly changed and always unified to the same characters. (Takashi Kokubun) * Don't preserve newlines in attributes. (Takashi Kokubun) * HTML escape interpolated code in filters. [#770](https://github.com/haml/haml/pull/770) (Matt Wildig) :javascript #{JSON.generate(foo: "bar")} Haml 4 output: {"foo":"bar"} Haml 5 output: {"foo":"bar"} Added * Add a tracing option. When enabled, Haml will output a data-trace attribute on each tag showing the path to the source Haml file from which it was generated. Thanks [Alex Babkin](https://github.com/ababkin). * Add `haml_tag_if` to render a block, conditionally wrapped in another element (Matt Wildig) * Support Rails 5.1 Erubi template handler. * Support Sprockets 3. Thanks [Sam Davies](https://github.com/samphilipd) and [Jeremy Venezia](https://github.com/jvenezia). * General performance and memory usage improvements. (Akira Matsuda) * Analyze attribute values by Ripper and render static attributes beforehand. (Takashi Kokubun) * Optimize attribute rendering about 3x faster. (Takashi Kokubun) * Add temple gem as dependency and create `Haml::TempleEngine` class. Some methods in `Haml::Compiler` are migrated to `Haml::TempleEngine`. (Takashi Kokubun) Fixed * Fix for attribute merging. When an attribute method (or literal nested hash) was used in an old style attribute hash and there is also a (non-static) new style hash there is an error. The fix can result in different behavior in some circumstances. See the [commit message](https://github.com/haml/haml/tree/e475b015d3171fb4c4f140db304f7970c787d6e3) for detailed info. (Matt Wildig) * Make escape_once respect hexadecimal references. (Matt Wildig) * Don't treat the 'data' attribute specially when merging attribute hashes. (Matt Wildig and Norman Clarke) * Fix #@foo and #$foo style interpolation that was not working in html_safe mode. (Akira Matsuda) * Allow `@` as tag's class name. Thanks [Joe Bartlett](https://github.com/redoPop). * Raise `Haml::InvalidAttributeNameError` when attribute name includes invalid characters. (Takashi Kokubun) * Don't ignore unexpected exceptions on initializing `ActionView::OutputBuffer`. (Takashi Kokubun) ## 4.0.7 Released on August 10, 2015 ([diff](https://github.com/haml/haml/compare/4.0.6...4.0.7)). * Significantly improve performance of regexp used to fix whitespace handling in textareas (thanks [Stan Hu](https://github.com/stanhu)). ## 4.0.6 Released on Dec 1, 2014 ([diff](https://github.com/haml/haml/compare/4.0.5...4.0.6)). * Fix warning on Ruby 1.8.7 "regexp has invalid interval" (thanks [Elia Schito](https://github.com/elia)). ## 4.0.5 Released on Jan 7, 2014 ([diff](https://github.com/haml/haml/compare/4.0.4...4.0.5)). * Fix haml_concat appending unescaped HTML after a call to haml_tag. * Fix for bug whereby when HAML :ugly option is "true", ActionView::Helpers::CaptureHelper::capture returns the whole view buffer when passed a block that returns nothing (thanks [Mircea Moise](https://github.com/mmircea16)). ## 4.0.4 Released on November 5, 2013 ([diff](https://github.com/haml/haml/compare/4.0.3...4.0.4)). * Check for Rails::Railtie rather than Rails (thanks [Konstantin Shabanov](https://github.com/etehtsea)). * Parser fix to allow literal '#' with suppress_eval (Matt Wildig). * Helpers#escape_once works on frozen strings (as does ERB::Util.html_escape_once for which it acts as a replacement in Rails (thanks [Patrik Metzmacher](https://github.com/patrik)). * Minor test fix (thanks [Mircea Moise](https://github.com/mmircea16)). ## 4.0.3 Released May 21, 2013 ([diff](https://github.com/haml/haml/compare/4.0.2...4.0.3)). * Compatibility with newer versions of Rails's Erubis handler. * Fix Erubis handler for compatibility with Tilt 1.4.x, too. * Small performance optimization for html_escape. (thanks [Lachlan Sylvester](https://github.com/lsylvester)) * Documentation fixes. * Documented some helper methods that were left out of the reference. (thanks [Shane Riley](https://github.com/shaneriley)) ## 4.0.2 Released April 5, 2013 ([diff](https://github.com/haml/haml/compare/4.0.1...4.0.2)). * Explicitly require Erubis to work around bug in older versions of Tilt. * Fix :erb filter printing duplicate content in Rails views. (thanks [Jori Hardman](https://github.com/jorihardman)) * Replace range with slice to reduce objects created by `capture_haml`. (thanks [Tieg Zaharia](https://github.com/tiegz)) * Correct/improve some documentation. ## 4.0.1 Released March 21, 2013 ([diff](https://github.com/haml/haml/compare/4.0.0...4.0.1)). * Remove Rails 3.2.3+ textarea hack in favor of a more general solution. * Fix some performance regressions. * Fix support for Rails 4 `text_area` helper method. * Fix data attribute flattening with singleton objects. (thanks [Alisdair McDiarmid](https://github.com/alisdair)) * Fix support for sass-rails 4.0 beta. (thanks [Ryunosuke SATO](https://github.com/tricknotes)) * Load "haml/template" in Railtie in order to prevent user options set in a Rails initializer from being overwritten * Don't depend on Rails in haml/template to allow using Haml with ActionView but without Rails itself. (thanks [Hunter Haydel](https://github.com/wedgex)) ## 4.0.0 * The Haml executable now accepts an `--autoclose` option. You can now specify a list of tags that should be autoclosed * The `:ruby` filter no longer redirects $stdout to the Haml document, as this is not thread safe. Instead it provides a `haml_io` local variable, which is an IO object that writes to the document. * HTML5 is now the default output format rather than XHTML. This was already the default on Rails 3+, so many users will notice no difference. * The :sass filter now wraps its output in a style tag, as do the new :less and :scss filters. The :coffee filter wraps its output in a script tag. * Haml now supports only Rails 3 and above, and Ruby 1.8.7 and above. If you still need support for Rails 2 and Ruby 1.8.6, please use Haml 3.1.x which will continue to be maintained for bug fixes. * The :javascript and :css filters no longer add CDATA tags when the format is html4 or html5. This can be overridden by setting the `cdata` option to `true`. CDATA tags are always added when the format is xhtml. * HTML2Haml has been extracted to a separate gem, creatively named "html2haml". * The `:erb` filter now uses Rails's safe output buffer to provide XSS safety. * Haml's internals have been refactored to move the parser, compiler and options handling into independent classes, rather than including them all in the Engine module. You can also specify your own custom Haml parser or compiler class in Haml::Options in order to extend or modify Haml reasonably easily. * Add an {file:REFERENCE.md#hyphenate_data_attrs-option `:hyphenate_data_attrs` option} that converts underscores to hyphens in your HTML5 data keys. This is a language change from 3.1 and is enabled by default. (thanks to [Andrew Smith](https://github.com/fullsailor)) * All Hash attribute values are now treated as HTML5 data, regardless of key. Previously only the "data" key was treated this way. Allowing arbitrary keys means you can now easily use this feature for Aria attributes, among other uses. (thanks to [Elvin Efendi](https://github.com/ElvinEfendi)) * Added `remove_whitespace` option to always remove all whitespace around Haml tags. (thanks to [Tim van der Horst](https://github.com/vdh)) * Haml now flattens deeply nested data attribute hashes. For example: `.foo{:data => {:a => "b", :c => {:d => "e", :f => "g"}}}` would render to: `
` (thanks to [Péter Pál Koszta](https://github.com/koszta)) * Filters that rely on third-party template engines are now implemented using [Tilt](http://github.com/rtomayko/tilt). Several new filters have been added, namely SCSS (:scss), LessCSS, (:less), and Coffeescript (:coffee/:coffeescript). Though the list of "official" filters is kept intentionally small, Haml comes with a helper method that makes adding support for other Tilt-based template engines trivial. As of 4.0, Haml will also ship with a "haml-contrib" gem that includes useful but less-frequently used filters and helpers. This includes several additional filters such as Nokogiri, Yajl, Markaby, and others. * Generate object references based on `#to_key` if it exists in preference to `#id`. * Performance improvements. (thanks to [Chris Heald](https://github.com/cheald)) * Helper `list_of` takes an extra argument that is rendered into list item attributes. (thanks [Iain Barnett](http://iainbarnett.me.uk/)) * Fix parser to allow lines ending with `some_method?` to be a Ruby multinline. (thanks to [Brad Ediger](https://github.com/bradediger)) * Always use :xhtml format when the mime_type of the rendered template is 'text/xml'. (thanks to [Stephen Bannasch](https://github.com/stepheneb)) * html2haml now includes an `--html-attributes` option. (thanks [Stefan Natchev](https://github.com/snatchev)) * Fix for inner whitespace removal in loops. (thanks [Richard Michael](https://github.com/richardkmichael)) * Use numeric character references rather than HTML entities when escaping double quotes and apostrophes in attributes. This works around some bugs in Internet Explorer earlier than version 9. (thanks [Doug Mayer](https://github.com/doxavore)) * Fix multiline silent comments: Haml previously did not allow free indentation inside multline silent comments. * Fix ordering bug with partial layouts on Rails. (thanks [Sam Pohlenz](https://github.com/spohlenz)) * Add command-line option to suppress script evaluation. * It's now possible to use Rails's asset helpers inside the Sass and SCSS filters. Note that to do so, you must make sure sass-rails is loaded in production, usually by moving it out of the assets gem group. * The Haml project now uses [semantic versioning](http://semver.org/). ## 3.2.0 The Haml 3.2 series was released only as far as 3.2.0.rc.4, but then was renamed to Haml 4.0 when the project adopted semantic versioning. ## 3.1.8 * Fix for line numbers reported from exceptions in nested blocks (thanks to Grant Hutchins & Sabrina Staedt). ## 3.1.7 * Fix for compatibility with Sass 3.2.x. (thanks [Michael Westbom](https://github.com/totallymike)). ## 3.1.6 * In indented mode, don't reindent buffers that contain preserved tags, and provide a better workaround for Rails 3.2.3's textarea helpers. ## 3.1.5 * Respect Rails' `html_safe` flag when escaping attribute values (thanks to [Gerad Suyderhoud](https://github.com/gerad)). * Fix for Rails 3.2.3 textarea helpers (thanks to [James Coleman](https://github.com/jcoleman) and others). ## 3.1.4 * Fix the use of `FormBuilder#block` with a label in Haml. * Fix indentation after a self-closing tag with dynamic attributes. ## 3.1.3 * Stop partial layouts from being displayed twice. ## 3.1.2 * If the ActionView `#capture` helper is used in a Haml template but without any Haml being run in the block, return the value of the block rather than the captured buffer. * Don't throw errors when text is nested within comments. * Fix html2haml. * Fix an issue where destructive modification was sometimes performed on Rails SafeBuffers. * Use character code entities for attribute value replacements instead of named/keyword entities. ## 3.1.1 * Update the vendored Sass to version 3.1.0. ## 3.1.0 * Don't add a `type` attribute to ` is now transformed into: :javascript function foo() { return 12; } * `
` and `
    

However, if a helper is generating the tag, Haml can't detect that and so you'll have to call {Haml::Helpers#find_and_preserve} yourself. You can also use `~`, which is the same as `=` except that it automatically runs `find_and_preserve` on its input. For example: %p= find_and_preserve "" is the same as %p~ "" and renders

### How do I make my long lines of Ruby code look nicer in my Haml document? {#q-multiline} Put them in a helper or your model. Haml purposefully makes it annoying to put lots of Ruby code into your templates, because lots of code doesn't belong in the view. If you take that huge `link_to_remote` call and move it to a `update_sidebar_link` helper, it'll make your view both easier to read and more semantic. If you absolutely must put lots of code in your template, Haml offers a somewhat awkward multiline-continuation tool. Put a `|` (pipe character) at the end of each line you want to be merged into one (including the last line!). For example: %p= @this.is(way.too.much). | code("and I should"). | really_move.it.into( | :a => @helper) | Note that sometimes it is valid to include lots of Ruby in a template when that Ruby is a helper call that passes in a lot of template information. Thus when a function has lots of arguments, it's possible to wrap it across multiple lines as long as each line ends in a comma. For example: = link_to_remote "Add to cart", :url => { :action => "add", :id => product.id }, :update => { :success => "cart", :failure => "error" } ### `form_for` is printing the form tag twice! Make sure you're calling it with `-`, not `=`. Just like in ERB, you have to do <% form_for stuff do %> ... <% end %> in Haml, you have to do - form_for stuff do ... ### I have Haml installed. Why is Rails (only looking for `.html.erb` files | rendering Haml files as plain text | rendering Haml files as blank pages)? {#q-blank-page} There are several reasons these things might be happening. First of all, make sure that Haml really is installed; either you've loaded the gem (via `config.gem` in Rails 2.3 or in the Gemfile in Rails 3), or `vendor/plugins/haml` exists and contains files. Then try restarting Mongrel or WEBrick or whatever you might be using. Finally, if none of these work, chances are you've got some localization plugin like Globalize installed. Such plugins often don't play nicely with Haml. Luckily, there's usually an easy fix. For Globalize, just edit `globalize/lib/globalize/rails/action_view.rb` and change @@re_extension = /\.(rjs|rhtml|rxml)$/ to @@re_extension = /\.(rjs|rhtml|rxml|erb|builder|haml)$/ For other plugins, a little searching will probably turn up a way to fix them as well. ## You still haven't answered my question! Sorry! Try looking at the [Haml](http://haml.info/docs/yardoc/file.REFERENCE.html) reference, If you can't find an answer there, feel free to ask in `#haml` on irc.freenode.net or send an email to the [mailing list](http://groups.google.com/group/haml). haml-5.1.2/Gemfile000066400000000000000000000003131352226600500137310ustar00rootroot00000000000000source "https://rubygems.org" gemspec gem "m" gem "pry" group :docs do gem "yard" gem "kramdown" gem "sass" end platform :mri do gem "ruby-prof" end platform :mri_21 do gem "simplecov" end haml-5.1.2/MIT-LICENSE000066400000000000000000000020761352226600500141020ustar00rootroot00000000000000Copyright (c) 2006-2019 Hampton Catlin and Natalie Weizenbaum Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. haml-5.1.2/README.md000066400000000000000000000140621352226600500137230ustar00rootroot00000000000000# Haml [![Gem Version](https://badge.fury.io/rb/haml.svg)](http://rubygems.org/gems/haml) [![Build Status](https://travis-ci.org/haml/haml.svg?branch=master)](http://travis-ci.org/haml/haml) [![Code Climate](https://codeclimate.com/github/haml/haml/badges/gpa.svg)](https://codeclimate.com/github/haml/haml) [![Coverage Status](http://img.shields.io/coveralls/haml/haml.svg)](https://coveralls.io/r/haml/haml) [![Inline docs](http://inch-ci.org/github/haml/haml.png)](http://inch-ci.org/github/haml/haml) Haml is a templating engine for HTML. It's designed to make it both easier and more pleasant to write HTML documents, by eliminating redundancy, reflecting the underlying structure that the document represents, and providing an elegant syntax that's both powerful and easy to understand. ## Basic Usage Haml can be used from the command line or as part of a Ruby web framework. The first step is to install the gem: ~~~sh gem install haml ~~~ After you write some Haml, you can run ~~~sh haml document.haml ~~~ to compile it to HTML. For more information on these commands, check out ~~~sh haml --help ~~~ To use Haml programatically, check out the [YARD documentation](http://haml.info/docs/yardoc/). ## Using Haml with Rails To use Haml with Rails, simply add Haml to your Gemfile and run `bundle`. ~~~ruby gem 'haml' ~~~ If you'd like to replace Rails's Erb-based generators with Haml, add [haml-rails](https://github.com/indirect/haml-rails) to your Gemfile as well. ## Formatting The most basic element of Haml is a shorthand for creating HTML: ~~~haml %tagname{:attr1 => 'value1', :attr2 => 'value2'} Contents ~~~ No end-tag is needed; Haml handles that automatically. If you prefer HTML-style attributes, you can also use: ~~~haml %tagname(attr1='value1' attr2='value2') Contents ~~~ Adding `class` and `id` attributes is even easier. Haml uses the same syntax as the CSS that styles the document: ~~~haml %tagname#id.class ~~~ In fact, when you're using the `
` tag, it becomes _even easier_. Because `
` is such a common element, a tag without a name defaults to a div. So ~~~haml #foo Hello! ~~~ becomes ~~~html
Hello!
~~~ Haml uses indentation to bring the individual elements to represent the HTML structure. A tag's children are indented beneath than the parent tag. Again, a closing tag is automatically added. For example: ~~~haml %ul %li Salt %li Pepper ~~~ becomes: ~~~html
  • Salt
  • Pepper
~~~ You can also put plain text as a child of an element: ~~~haml %p Hello, World! ~~~ It's also possible to embed Ruby code into Haml documents. An equals sign, `=`, will output the result of the code. A hyphen, `-`, will run the code but not output the result. You can even use control statements like `if` and `while`: ~~~haml %p Date/Time: - now = DateTime.now %strong= now - if now > DateTime.parse("December 31, 2006") = "Happy new " + "year!" ~~~ Haml provides far more tools than those presented here. Check out the [reference documentation](http://haml.info/docs/yardoc/file.REFERENCE.html) for full details. ### Indentation Haml's indentation can be made up of one or more tabs or spaces. However, indentation must be consistent within a given document. Hard tabs and spaces can't be mixed, and the same number of tabs or spaces must be used throughout. ## Contributing Contributions are welcomed, but before you get started please read the [guidelines](http://haml.info/development.html#contributing). After forking and then cloning the repo locally, install Bundler and then use it to install the development gem dependencies: ~~~sh gem install bundler bundle install ~~~ Once this is complete, you should be able to run the test suite: ~~~sh rake ~~~ You'll get a warning that you need to install haml-spec, so run this: ~~~sh git submodule update --init ~~~ At this point `rake` should run without error or warning and you are ready to start working on your patch! Note that you can also run just one test out of the test suite if you're working on a specific area: ~~~sh ruby -Itest test/helper_test.rb -n test_buffer_access ~~~ Haml currently supports Ruby 2.0.0 and higher, so please make sure your changes run on 2.0+. ## Team ### Current Maintainers * [Akira Matsuda](https://github.com/amatsuda) * [Matt Wildig](https://github.com/mattwildig) * [Tee Parham](https://github.com/teeparham) * [Takashi Kokubun](https://github.com/k0kubun) ### Alumni Haml was created by [Hampton Catlin](http://hamptoncatlin.com), the author of the original implementation. Hampton is no longer involved in day-to-day coding, but still consults on language issues. [Natalie Weizenbaum](http://nex-3.com) was for many years the primary developer and architect of the "modern" Ruby implementation of Haml. [Norman Clarke](http://github.com/norman) was the primary maintainer of Haml from 2012 to 2016. ## License Some of Natalie's work on Haml was supported by Unspace Interactive. Beyond that, the implementation is licensed under the MIT License. Copyright (c) 2006-2019 Hampton Catlin, Natalie Weizenbaum and the Haml team Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. haml-5.1.2/REFERENCE.md000066400000000000000000001142421352226600500142650ustar00rootroot00000000000000# Haml (HTML Abstraction Markup Language) Haml is a markup language that's used to cleanly and simply describe the HTML of any web document, without the use of inline code. Haml functions as a replacement for inline page templating systems such as PHP, ERB, and ASP. However, Haml avoids the need for explicitly coding HTML into the template, because it is actually an abstract description of the HTML, with some code to generate dynamic content. ## Features * Whitespace active * Well-formatted markup * DRY * Follows CSS conventions * Integrates Ruby code * Implements Rails templates with the .haml extension ## Using Haml Haml can be used in three ways: * as a command-line tool, * as a plugin for Ruby on Rails, * and as a standalone Ruby module. The first step for all of these is to install the Haml gem: gem install haml To run Haml from the command line, just use haml input.haml output.html Use `haml --help` for full documentation. To use Haml with Rails, add the following line to the Gemfile: gem "haml" Once it's installed, all view files with the `".html.haml"` extension will be compiled using Haml. You can access instance variables in Haml templates the same way you do in ERB templates. Helper methods are also available in Haml templates. For example: # file: app/controllers/movies_controller.rb class MoviesController < ApplicationController def index @title = "Teen Wolf" end end -# file: app/views/movies/index.html.haml #content .title %h1= @title = link_to 'Home', home_url may be compiled to:

Teen Wolf

Home
### Rails XSS Protection Haml supports Rails' XSS protection scheme, which was introduced in Rails 2.3.5+ and is enabled by default in 3.0.0+. If it's enabled, Haml's {Haml::Options#escape_html `:escape_html`} option is set to `true` by default - like in ERB, all strings printed to a Haml template are escaped by default. Also like ERB, strings marked as HTML safe are not escaped. Haml also has [its own syntax for printing a raw string to the template](#unescaping_html). If the `:escape_html` option is set to false when XSS protection is enabled, Haml doesn't escape Ruby strings by default. However, if a string marked HTML-safe is passed to [Haml's escaping syntax](#escaping_html), it won't be escaped. Finally, all the {Haml::Helpers Haml helpers} that return strings that are known to be HTML safe are marked as such. In addition, string input is escaped unless it's HTML safe. ### Ruby Module Haml can also be used completely separately from Rails and ActionView. To do this, install the gem with RubyGems: gem install haml You can then use it by including the "haml" gem in Ruby code, and using {Haml::Engine} like so: engine = Haml::Engine.new("%p Haml code!") engine.render #=> "

Haml code!

\n" ### Options Haml understands various configuration options that affect its performance and output. In Rails, options can be set by setting the {Haml::Template#options Haml::Template.options} hash in an initializer: # config/initializers/haml.rb Haml::Template.options[:format] = :html5 Outside Rails, you can set them by configuring them globally in Haml::Options.defaults: Haml::Options.defaults[:format] = :html5 In sinatra specifically, you can set them in global config with: ```ruby set :haml, { escape_html: true } ``` Finally, you can also set them by passing an options hash to {Haml::Engine#initialize}. For the complete list of available options, please see {Haml::Options}. ### Encodings Haml supports the same sorts of encoding-declaration comments that Ruby does. Although both Ruby and Haml support several different styles, the easiest it just to add `-# coding: encoding-name` at the beginning of the Haml template (it must come before all other lines). This will tell Haml that the template is encoded using the named encoding. By default, the HTML generated by Haml has the same encoding as the Haml template. However, if `Encoding.default_internal` is set, Haml will attempt to use that instead. In addition, the {Haml::Options#encoding `:encoding` option} can be used to specify an output encoding manually. Note that, like Ruby, Haml does not support templates encoded in UTF-16 or UTF-32, since these encodings are not compatible with ASCII. It is possible to use these as the output encoding, though. ## Plain Text A substantial portion of any HTML document is its content, which is plain old text. Any Haml line that's not interpreted as something else is taken to be plain text, and passed through unmodified. For example: %gee %whiz Wow this is cool! is compiled to: Wow this is cool! Note that HTML tags are passed through unmodified as well. If you have some HTML you don't want to convert to Haml, or you're converting a file line-by-line, you can just include it as-is. For example: %p
Blah!
is compiled to:

Blah!

### Escaping: `\` The backslash character escapes the first character of a line, allowing use of otherwise interpreted characters as plain text. For example: %title = @title \= @title is compiled to: MyPage = @title ## HTML Elements ### Element Name: `%` The percent character is placed at the beginning of a line. It's followed immediately by the name of an element, then optionally by modifiers (see below), a space, and text to be rendered inside the element. It creates an element in the form of ``. For example: %one %two %three Hey there is compiled to: Hey there Any string is a valid element name; Haml will automatically generate opening and closing tags for any element. ### Attributes: `{}` or `()` {#attributes} Brackets represent a Ruby hash that is used for specifying the attributes of an element. It is literally evaluated as a Ruby hash, so logic will work in it and local variables may be used. Quote characters within the attribute will be replaced by appropriate escape sequences. The hash is placed after the tag is defined. For example: %html{:xmlns => "http://www.w3.org/1999/xhtml", "xml:lang" => "en", :lang => "en"} is compiled to: Attribute hashes can also be stretched out over multiple lines to accommodate many attributes. However, newlines may only be placed immediately after commas. For example: %script{:type => "text/javascript", :src => "javascripts/script_#{2 + 7}"} is compiled to: #### `:class` and `:id` Attributes {#class-and-id-attributes} The `:class` and `:id` attributes can also be specified as a Ruby array whose elements will be joined together. A `:class` array is joined with `" "` and an `:id` array is joined with `"_"`. For example: %div{:id => [@item.type, @item.number], :class => [@item.type, @item.urgency]} is equivalent to: %div{:id => "#{@item.type}_#{@item.number}", :class => "#{@item.type} #{@item.urgency}"} The array will first be flattened and any elements that do not test as true will be removed. The remaining elements will be converted to strings. For example: %div{:class => [@item.type, @item == @sortcol && [:sort, @sortdir]] } Contents could render as any of:
Contents
Contents
Contents
Contents
depending on whether `@item.type` is `"numeric"` or `nil`, whether `@item == @sortcol`, and whether `@sortdir` is `"ascending"` or `"descending"`. If a single value is specified and it evaluates to false it is ignored; otherwise it gets converted to a string. For example: .item{:class => @item.is_empty? && "empty"} could render as either of: class="item" class="item empty" #### HTML-style Attributes: `()` Haml also supports a terser, less Ruby-specific attribute syntax based on HTML's attributes. These are used with parentheses instead of brackets, like so: %html(xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en") Ruby variables can be used by omitting the quotes. Local variables or instance variables can be used. For example: %a(title=@title href=href) Stuff This is the same as: %a{:title => @title, :href => href} Stuff Because there are no commas separating attributes, though, more complicated expressions aren't allowed. For those you'll have to use the `{}` syntax. You can, however, use both syntaxes together: %a(title=@title){:href => @link.href} Stuff You can also use `#{}` interpolation to insert complicated expressions in a HTML-style attribute: %span(class="widget_#{@widget.number}") HTML-style attributes can be stretched across multiple lines just like hash-style attributes: %script(type="text/javascript" src="javascripts/script_#{2 + 7}") #### Ruby 1.9-style Hashes Haml also supports Ruby's new hash syntax: %a{title: @title, href: href} Stuff #### Attribute Methods A Ruby method call that returns a hash can be substituted for the hash contents. For example, {Haml::Helpers} defines the following method: def html_attrs(lang = 'en-US') {:xmlns => "http://www.w3.org/1999/xhtml", 'xml:lang' => lang, :lang => lang} end This can then be used in Haml, like so: %html{html_attrs('fr-fr')} This is compiled to: You can use as many such attribute methods as you want by separating them with commas, like a Ruby argument list. All the hashes will be merged together, from left to right. For example, if you defined def hash1 {:bread => 'white', :filling => 'peanut butter and jelly'} end def hash2 {:bread => 'whole wheat'} end then %sandwich{hash1, hash2, :delicious => 'true'}/ would compile to: Note that the Haml attributes list has the same syntax as a Ruby method call. This means that any attribute methods must come before the hash literal. Attribute methods aren't supported for HTML-style attributes. #### Boolean Attributes Some attributes, such as "checked" for `input` tags or "selected" for `option` tags, are "boolean" in the sense that their values don't matter - it only matters whether or not they're present. In HTML (but not XHTML), these attributes can be written as To do this in Haml using hash-style attributes, just assign a Ruby `true` value to the attribute: %input{:selected => true} In XHTML, the only valid value for these attributes is the name of the attribute. Thus this will render in XHTML as To set these attributes to false, simply assign them to a Ruby false value. In both XHTML and HTML, %input{:selected => false} will just render as: HTML-style boolean attributes can be written just like HTML: %input(selected) or using `true` and `false`: %input(selected=true) #### Prefixed Attributes HTML5 allows for adding [custom non-visible data attributes](http://www.whatwg.org/specs/web-apps/current-work/multipage/elements.html#embedding-custom-non-visible-data-with-the-data-*-attributes) to elements using attribute names beginning with `data-`. The [Accessible Rich Internet Applications](http://www.w3.org/WAI/intro/aria) specification makes use of attributes beginning with `aria-`. There are also frameworks that use non-standard attributes with a common prefix. Haml can help generate collections of attributes that share a prefix like these. Any entry in an attribute hash that has a Hash as its value is expanded into a series of attributes, one for each key/value pair in the hash, with the attribute name formed by joining the “parent” key name to the key name with a hyphen. For example: %a{:href=>"/posts", :data => {:author_id => 123, :category => 7}} Posts By Author will render as: Posts By Author Notice that the underscore in `author_id` was replaced by a hyphen. If you wish to suppress this behavior, you can set Haml's {Haml::Options#hyphenate_data_attrs `:hyphenate_data_attrs` option} to `false`, and the output will be rendered as: Posts By Author This expansion of hashes is recursive – any value of the child hash that is itself a hash will create an attribute for each entry, with the attribute name prefixed with all ancestor keys. For example: .book-info{:data => {:book => {:id => 123, :genre => 'programming'}, :category => 7}} will render as:
### Class and ID: `.` and `#` The period and pound sign are borrowed from CSS. They are used as shortcuts to specify the `class` and `id` attributes of an element, respectively. Multiple class names can be specified in a similar way to CSS, by chaining the class names together with periods. They are placed immediately after the tag and before an attributes hash. For example: %div#things %span#rice Chicken Fried %p.beans{ :food => 'true' } The magical fruit %h1.class.otherclass#id La La La is compiled to:
Chicken Fried

The magical fruit

La La La

And, %div#content %div.articles %div.article.title Doogie Howser Comes Out %div.article.date 2006-11-05 %div.article.entry Neil Patrick Harris would like to dispel any rumors that he is straight is compiled to:
Doogie Howser Comes Out
2006-11-05
Neil Patrick Harris would like to dispel any rumors that he is straight
These shortcuts can be combined with long-hand attributes; the two values will be merged together as though they were all placed in an array (see [the documentation on `:class` and `:id` attributes](#class-and-id-attributes)). For example: %div#Article.article.entry{:id => @article.number, :class => @article.visibility} is equivalent to %div{:id => ['Article', @article.number], :class => ['article', 'entry', @article.visibility]} Gabba Hey and could compile to:
Gabba Hey
#### Implicit Div Elements Because divs are used so often, they're the default elements. If you only define a class and/or id using `.` or `#`, a div is automatically used. For example: #collection .item .description What a cool item! is the same as: %div#collection %div.item %div.description What a cool item! and is compiled to:
What a cool item!
### Empty (void) Tags: `/` The forward slash character, when placed at the end of a tag definition, causes Haml to treat it as being an empty (or void) element. Depending on the format, the tag will be rendered either without a closing tag (`:html4` or `:html5`), or as a self-closing tag (`:xhtml`). Taking the following as an example: %br/ %meta{'http-equiv' => 'Content-Type', :content => 'text/html'}/ When the format is `:html4` or `:html5` this is compiled to:
and when the format is `:xhtml` it is compiled to:
Some tags are automatically treated as being empty, as long as they have no content in the Haml source. `meta`, `img`, `link`, `br`, `hr`, `input`, `area`, `param`, `col` and `base` tags are treated as empty by default. This list can be customized by setting the {Haml::Options#autoclose `:autoclose`} option. ### Whitespace Removal: `>` and `<` `>` and `<` give you more control over the whitespace near a tag. `>` will remove all whitespace surrounding a tag, while `<` will remove all whitespace immediately within a tag. You can think of them as alligators eating the whitespace: `>` faces out of the tag and eats the whitespace on the outside, and `<` faces into the tag and eats the whitespace on the inside. They're placed at the end of a tag definition, after class, id, and attribute declarations but before `/` or `=`. For example: %blockquote< %div Foo! is compiled to:
Foo!
And: %img %img> %img is compiled to: And: %p<= "Foo\nBar" is compiled to:

Foo Bar

And finally: %img %pre>< foo bar %img is compiled to:
foo
    bar
### Object Reference: `[]` Square brackets follow a tag definition and contain a Ruby object that is used to set the class and id of that tag. The class is set to the object's class (transformed to use underlines rather than camel case) and the id is set to the object's class, followed by the value of its `#to_key` or `#id` method (in that order). This is most useful for elements that represent instances of Active Model models. Additionally, the second argument (if present) will be used as a prefix for both the id and class attributes. For example: # file: app/controllers/users_controller.rb def show @user = CrazyUser.find(15) end -# file: app/views/users/show.haml %div[@user, :greeting] %bar[290]/ Hello! is compiled to:
Hello!
If you require that the class be something other than the underscored object's class, you can implement the `haml_object_ref` method on the object. # file: app/models/crazy_user.rb class CrazyUser < ActiveRecord::Base def haml_object_ref "a_crazy_user" end end -# file: app/views/users/show.haml %div[@user] Hello! is compiled to:
Hello!
The `:class` attribute may be used in conjunction with an object reference. The compiled element will have the union of all classes. - user = User.find(1) %p[user]{:class => 'alpha bravo'}

## Doctype: `!!!` When describing HTML documents with Haml, you can have a document type or XML prolog generated automatically by including the characters `!!!`. For example: !!! XML !!! %html %head %title Myspace %body %h1 I am the international space station %p Sign my guestbook is compiled to: Myspace

I am the international space station

Sign my guestbook

You can also specify the specific doctype after the `!!!` When the {Haml::Options#format `:format`} is set to `:xhtml`. The following doctypes are supported: `!!!` : XHTML 1.0 Transitional
`` `!!! Strict` : XHTML 1.0 Strict
`` `!!! Frameset` : XHTML 1.0 Frameset
`` `!!! 5` : XHTML 5
``
`!!! 1.1` : XHTML 1.1
`` `!!! Basic` : XHTML Basic 1.1
` ` `!!! Mobile` : XHTML Mobile 1.2
`` `!!! RDFa` : XHTML+RDFa 1.0
`` When the {Haml::Options#format `:format`} option is set to `:html4`, the following doctypes are supported: `!!!` : HTML 4.01 Transitional
`` `!!! Strict` : HTML 4.01 Strict
`` `!!! Frameset` : HTML 4.01 Frameset
`` When the {Haml::Options#format `:format`} option is set to `:html5`, `!!!` is always ``. If you're not using the UTF-8 character set for your document, you can specify which encoding should appear in the XML prolog in a similar way. For example: !!! XML iso-8859-1 is compiled to: If the mime_type of the template being rendered is `text/xml` then a format of `:xhtml` will be used even if the global output format is set to `:html4` or `:html5`. ## Comments Haml supports two sorts of comments: those that show up in the HTML output and those that don't. ### HTML Comments: `/` The forward slash character, when placed at the beginning of a line, wraps all text after it in an HTML comment. For example: %peanutbutterjelly / This is the peanutbutterjelly element I like sandwiches! is compiled to: I like sandwiches! The forward slash can also wrap indented sections of code. For example: / %p This doesn't render... %div %h1 Because it's commented out! is compiled to: #### Conditional Comments: `/[]` You can also use [Internet Explorer conditional comments](http://www.quirksmode.org/css/condcom.html) by enclosing the condition in square brackets after the `/`. For example: /[if IE] %a{ :href => 'http://www.mozilla.com/en-US/firefox/' } %h1 Get Firefox is compiled to: To generate “downlevel-revealed” conditional comments, where the content is hidden from IE but not other browsers, add a `!` before the brackets: `/![]`. Haml will produce valid HTML when generating this kind of conditional comment. For example: /![if !IE] You are not using Internet Explorer, or are using version 10+. is compiled to: You are not using Internet Explorer, or are using version 10+. ### Haml Comments: `-#` The hyphen followed immediately by the pound sign signifies a silent comment. Any text following this isn't rendered in the resulting document at all. For example: %p foo -# This is a comment %p bar is compiled to:

foo

bar

You can also nest text beneath a silent comment. None of this text will be rendered. For example: %p foo -# This won't be displayed Nor will this Nor will this. %p bar is compiled to:

foo

bar

## Ruby Evaluation ### Inserting Ruby: `=` The equals character is followed by Ruby code. This code is evaluated and the output is inserted into the document. For example: %p = ['hi', 'there', 'reader!'].join " " = "yo" is compiled to:

hi there reader! yo

If the {Haml::Options#escape_html `:escape_html`} option is set, `=` will sanitize any HTML-sensitive characters generated by the script. For example: = '' would be compiled to <script>alert("I'm evil!");</script> `=` can also be used at the end of a tag to insert Ruby code within that tag. For example: %p= "hello" would be compiled to:

hello

A line of Ruby code can be stretched over multiple lines as long as each line but the last ends with a comma. For example: = link_to_remote "Add to cart", :url => { :action => "add", :id => product.id }, :update => { :success => "cart", :failure => "error" } Note that it's illegal to nest code within a tag that ends with `=`. ### Running Ruby: `-` The hyphen character is also followed by Ruby code. This code is evaluated but *not* inserted into the document. **It is not recommended that you use this widely; almost all processing code and logic should be restricted to Controllers, Helpers, or partials.** For example: - foo = "hello" - foo << " there" - foo << " you!" %p= foo is compiled to:

hello there you!

A line of Ruby code can be stretched over multiple lines as long as each line but the last ends with a comma. For example: - links = {:home => "/", :docs => "/docs", :about => "/about"} #### Ruby Blocks Ruby blocks, like XHTML tags, don't need to be explicitly closed in Haml. Rather, they're automatically closed, based on indentation. A block begins whenever the indentation is increased after a Ruby evaluation command. It ends when the indentation decreases (as long as it's not an `else` clause or something similar). For example: - (42...47).each do |i| %p= i %p See, I can count! is compiled to:

42

43

44

45

46

See, I can count!

Another example: %p - case 2 - when 1 = "1!" - when 2 = "2?" - when 3 = "3." is compiled to:

2?

### Whitespace Preservation: `~` {#tilde} `~` works just like `=`, except that it runs {Haml::Helpers#find\_and\_preserve} on its input. For example, ~ "Foo\n
Bar\nBaz
" is the same as: = find_and_preserve("Foo\n
Bar\nBaz
") and is compiled to: Foo
Bar
Baz
See also [Whitespace Preservation](#whitespace_preservation). ### Ruby Interpolation: `#{}` Ruby code can also be interpolated within plain text using `#{}`, similarly to Ruby string interpolation. For example, %p This is #{h quality} cake! is the same as %p= "This is #{h quality} cake!" and might compile to:

This is scrumptious cake!

Backslashes can be used to escape `#{}` strings, but they don't act as escapes anywhere else in the string. For example: %p Look at \\#{h word} lack of backslash: \#{foo} And yon presence thereof: \{foo} might compile to:

Look at \yon lack of backslash: #{foo} And yon presence thereof: \{foo}

Interpolation can also be used within [filters](#filters). For example: :javascript $(document).ready(function() { alert(#{@message.to_json}); }); might compile to: #### Gotchas Haml uses an overly simplistic regular expression to identify string interpolation rather than a full-blown Ruby parser. This is fast and works for most code but you may have errors with code like the following: %span #{'{'} This code will generate a syntax error, complaining about unbalanced brackets. In cases like this, the recommended workaround is output the code as a Ruby string to force Haml to parse the code with Ruby. %span= "#{'{'}" ### Escaping HTML: `&=` {#escaping_html} An ampersand followed by one or two equals characters evaluates Ruby code just like the equals without the ampersand, but sanitizes any HTML-sensitive characters in the result of the code. For example: &= "I like cheese & crackers" compiles to I like cheese & crackers If the {Haml::Options#escape_html `:escape_html`} option is set, `&=` behaves identically to `=`. `&` can also be used on its own so that `#{}` interpolation is escaped. For example, & I like #{"cheese & crackers"} compiles to: I like cheese & crackers ### Unescaping HTML: `!=` {#unescaping_html} An exclamation mark followed by one or two equals characters evaluates Ruby code just like the equals would, but never sanitizes the HTML. By default, the single equals doesn't sanitize HTML either. However, if the {Haml::Options#escape_html `:escape_html`} option is set, `=` will sanitize the HTML, but `!=` still won't. For example, if `:escape_html` is set: = "I feel !" != "I feel !" compiles to I feel <strong>! I feel ! `!` can also be used on its own so that `#{}` interpolation is unescaped. For example, ! I feel #{""}! compiles to I feel ! ## Filters {#filters} The colon character designates a filter. This allows you to pass an indented block of text as input to another filtering program and add the result to the output of Haml. The syntax is simply a colon followed by the name of the filter. For example: %p :markdown # Greetings Hello, *World* is compiled to:

Greetings

Hello, World

Filters can have Ruby code interpolated with `#{}`. For example: - flavor = "raspberry" #content :textile I *really* prefer _#{flavor}_ jam. is compiled to

I really prefer raspberry jam.

Note that `#{}` interpolation within filters is HTML-escaped if you specify true to {Haml::Options#escape_filter_interpolations `:escape_filter_interpolations`} option. The functionality of some filters such as Markdown can be provided by many different libraries. Usually you don't have to worry about this - you can just load the gem of your choice and Haml will automatically use it. However in some cases you may want to make Haml explicitly use a specific gem to be used by a filter. In these cases you can do this via Tilt, the library Haml uses to implement many of its filters: Tilt.prefer Tilt::RedCarpetTemplate See the [Tilt documentation](https://github.com/rtomayko/tilt#fallback-mode) for more info. Haml comes with the following filters defined: ### `:cdata` {#cdata-filter} Surrounds the filtered text with CDATA tags. ### `:coffee` {#coffee-filter} Compiles the filtered text to JavaScript in `! end end # Surrounds the filtered text with `) end end # Surrounds the filtered text with CDATA tags. module Cdata include Base # @see Base#render def render(text) "" end end # Works the same as {Plain}, but HTML-escapes the text before placing it in # the document. module Escaped include Base # @see Base#render def render(text) Haml::Helpers.html_escape text end end # Parses the filtered text with the normal Ruby interpreter. Creates an IO # object named `haml_io`, anything written to it is output into the Haml # document. In previous version this filter redirected any output to `$stdout` # to the Haml document, this was not threadsafe and has been removed, you # should use `haml_io` instead. # # Not available if the {file:REFERENCE.md#suppress_eval-option `:suppress_eval`} # option is set to true. The Ruby code is evaluated in the same context as # the Haml template. module Ruby include Base require 'stringio' # @see Base#compile def compile(compiler, text) return if compiler.options[:suppress_eval] compiler.instance_eval do push_silent "#{<<-FIRST.tr("\n", ';')}#{text}#{<<-LAST.tr("\n", ';')}" begin haml_io = StringIO.new(_hamlout.buffer, 'a') FIRST ensure haml_io.close haml_io = nil end LAST end end end # Inserts the filtered text into the template with whitespace preserved. # `preserve`d blocks of text aren't indented, and newlines are replaced with # the HTML escape code for newlines, to preserve nice-looking output. # # @see Haml::Helpers#preserve module Preserve include Base # @see Base#render def render(text) Haml::Helpers.preserve text end end # @private module TiltFilter extend self attr_accessor :tilt_extension, :options attr_writer :template_class def template_class (@template_class if defined? @template_class) or begin @template_class = Tilt["t.#{tilt_extension}"] or raise Error.new(Error.message(:cant_run_filter, tilt_extension)) rescue LoadError => e dep = e.message.split('--').last.strip raise Error.new(Error.message(:gem_install_filter_deps, tilt_extension, dep)) end end def self.extended(base) base.options = {} # There's a bug in 1.9.2 where the same parse tree cannot be shared # across several singleton classes -- this bug is fixed in 1.9.3. # We work around this by using a string eval instead of a block eval # so that a new parse tree is created for each singleton class. base.instance_eval %Q{ include Base def render_with_options(text, compiler_options) text = template_class.new(nil, 1, options) {text}.render super(text, compiler_options) end } end end # @private module PrecompiledTiltFilter def precompiled(text) template_class.new(nil, 1, options) { text }.send(:precompiled, {}).first end def compile(compiler, text) return if compiler.options[:suppress_eval] compiler.send(:push_script, precompiled(text)) end end # @!parse module Sass; end register_tilt_filter "Sass", :extend => "Css" # @!parse module Scss; end register_tilt_filter "Scss", :extend => "Css" # @!parse module Less; end register_tilt_filter "Less", :extend => "Css" # @!parse module Markdown; end register_tilt_filter "Markdown" # @!parse module Erb; end register_tilt_filter "Erb", :precompiled => true # @!parse module Coffee; end register_tilt_filter "Coffee", :alias => "coffeescript", :extend => "Javascript" # Parses the filtered text with ERB. # Not available if the {file:REFERENCE.md#suppress_eval-option # `:suppress_eval`} option is set to true. Embedded Ruby code is evaluated # in the same context as the Haml template. module Erb class << self def precompiled(text) #workaround for https://github.com/rtomayko/tilt/pull/183 require 'erubis' if (defined?(::Erubis) && !defined?(::Erubis::Eruby)) super.sub(/^#coding:.*?\n/, '') end end end end end # These filters have been demoted to Haml Contrib but are still included by # default in Haml 4.0. Still, we rescue from load error if for some reason # haml-contrib is not installed. begin require "haml/filters/maruku" require "haml/filters/textile" rescue LoadError end haml-5.1.2/lib/haml/generator.rb000066400000000000000000000014471352226600500164510ustar00rootroot00000000000000# frozen_string_literal: true module Haml # Ruby code generator, which is a limited version of Temple::Generator. # Limit methods since Haml doesn't need most of them. class Generator include Temple::Mixins::CompiledDispatcher include Temple::Mixins::Options define_options freeze_static: RUBY_VERSION >= '2.1' def call(exp) compile(exp) end def on_multi(*exp) exp.map { |e| compile(e) }.join('; ') end def on_static(text) concat(options[:freeze_static] ? "#{Util.inspect_obj(text)}.freeze" : Util.inspect_obj(text)) end def on_dynamic(code) concat(code) end def on_code(exp) exp end def on_newline "\n" end private def concat(str) "_hamlout.buffer << (#{str});" end end end haml-5.1.2/lib/haml/helpers.rb000066400000000000000000000535061352226600500161300ustar00rootroot00000000000000# frozen_string_literal: true require 'erb' module Haml # This module contains various helpful methods to make it easier to do various tasks. # {Haml::Helpers} is automatically included in the context # that a Haml template is parsed in, so all these methods are at your # disposal from within the template. module Helpers # An object that raises an error when \{#to\_s} is called. # It's used to raise an error when the return value of a helper is used # when it shouldn't be. class ErrorReturn def initialize(method) @message = < e e.backtrace.shift # If the ErrorReturn is used directly in the template, # we don't want Haml's stuff to get into the backtrace, # so we get rid of the format_script line. # # We also have to subtract one from the Haml line number # since the value is passed to format_script the line after # it's actually used. if e.backtrace.first =~ /^\(eval\):\d+:in `format_script/ e.backtrace.shift e.backtrace.first.gsub!(/^\(haml\):(\d+)/) {|s| "(haml):#{$1.to_i - 1}"} end raise e end # @return [String] A human-readable string representation def inspect "Haml::Helpers::ErrorReturn(#{@message.inspect})" end end self.extend self @@action_view_defined = false # @return [Boolean] Whether or not ActionView is loaded def self.action_view? @@action_view_defined end # Note: this does **not** need to be called when using Haml helpers # normally in Rails. # # Initializes the current object as though it were in the same context # as a normal ActionView instance using Haml. # This is useful if you want to use the helpers in a context # other than the normal setup with ActionView. # For example: # # context = Object.new # class << context # include Haml::Helpers # end # context.init_haml_helpers # context.haml_tag :p, "Stuff" # def init_haml_helpers @haml_buffer = Haml::Buffer.new(haml_buffer, Options.new.for_buffer) nil end # Runs a block of code in a non-Haml context # (i.e. \{#is\_haml?} will return false). # # This is mainly useful for rendering sub-templates such as partials in a non-Haml language, # particularly where helpers may behave differently when run from Haml. # # Note that this is automatically applied to Rails partials. # # @yield A block which won't register as Haml def non_haml was_active = @haml_buffer.active? @haml_buffer.active = false yield ensure @haml_buffer.active = was_active end # Uses \{#preserve} to convert any newlines inside whitespace-sensitive tags # into the HTML entities for endlines. # # @param tags [Array] Tags that should have newlines escaped # # @overload find_and_preserve(input, tags = haml_buffer.options[:preserve]) # Escapes newlines within a string. # # @param input [String] The string within which to escape newlines # @overload find_and_preserve(tags = haml_buffer.options[:preserve]) # Escapes newlines within a block of Haml code. # # @yield The block within which to escape newlines def find_and_preserve(input = nil, tags = haml_buffer.options[:preserve], &block) return find_and_preserve(capture_haml(&block), input || tags) if block tags = tags.map { |tag| Regexp.escape(tag) }.join('|') re = /<(#{tags})([^>]*)>(.*?)(<\/\1>)/im input.to_s.gsub(re) do |s| s =~ re # Can't rely on $1, etc. existing since Rails' SafeBuffer#gsub is incompatible "<#{$1}#{$2}>#{preserve($3)}" end end # Takes any string, finds all the newlines, and converts them to # HTML entities so they'll render correctly in # whitespace-sensitive tags without screwing up the indentation. # # @overload preserve(input) # Escapes newlines within a string. # # @param input [String] The string within which to escape all newlines # @overload preserve # Escapes newlines within a block of Haml code. # # @yield The block within which to escape newlines def preserve(input = nil, &block) return preserve(capture_haml(&block)) if block s = input.to_s.chomp("\n") s.gsub!(/\n/, ' ') s.delete!("\r") s end alias_method :flatten, :preserve # Takes an `Enumerable` object and a block # and iterates over the enum, # yielding each element to a Haml block # and putting the result into `
  • ` elements. # This creates a list of the results of the block. # For example: # # = list_of([['hello'], ['yall']]) do |i| # = i[0] # # Produces: # #
  • hello
  • #
  • yall
  • # # And: # # = list_of({:title => 'All the stuff', :description => 'A book about all the stuff.'}) do |key, val| # %h3= key.humanize # %p= val # # Produces: # #
  • #

    Title

    #

    All the stuff

    #
  • #
  • #

    Description

    #

    A book about all the stuff.

    #
  • # # While: # # = list_of(["Home", "About", "Contact", "FAQ"], {class: "nav", role: "nav"}) do |item| # %a{ href="#" }= item # # Produces: # # # # # # # `[[class", "nav"], [role", "nav"]]` could have been used instead of `{class: "nav", role: "nav"}` (or any enumerable collection where each pair of items responds to #to_s) # # @param enum [Enumerable] The list of objects to iterate over # @param [Enumerable<#to_s,#to_s>] opts Each key/value pair will become an attribute pair for each list item element. # @yield [item] A block which contains Haml code that goes within list items # @yieldparam item An element of `enum` def list_of(enum, opts={}, &block) opts_attributes = opts.map { |k, v| " #{k}='#{v}'" }.join enum.map do |i| result = capture_haml(i, &block) if result.count("\n") > 1 result.gsub!("\n", "\n ") result = "\n #{result.strip}\n" else result.strip! end %Q!#{result}! end.join("\n") end # Returns a hash containing default assignments for the `xmlns`, `lang`, and `xml:lang` # attributes of the `html` HTML element. # For example, # # %html{html_attrs} # # becomes # # # # @param lang [String] The value of `xml:lang` and `lang` # @return [{#to_s => String}] The attribute hash def html_attrs(lang = 'en-US') if haml_buffer.options[:format] == :xhtml {:xmlns => "http://www.w3.org/1999/xhtml", 'xml:lang' => lang, :lang => lang} else {:lang => lang} end end # Increments the number of tabs the buffer automatically adds # to the lines of the template. # For example: # # %h1 foo # - tab_up # %p bar # - tab_down # %strong baz # # Produces: # #

    foo

    #

    bar

    # baz # # @param i [Fixnum] The number of tabs by which to increase the indentation # @see #tab_down def tab_up(i = 1) haml_buffer.tabulation += i end # Decrements the number of tabs the buffer automatically adds # to the lines of the template. # # @param i [Fixnum] The number of tabs by which to decrease the indentation # @see #tab_up def tab_down(i = 1) haml_buffer.tabulation -= i end # Sets the number of tabs the buffer automatically adds # to the lines of the template, # but only for the duration of the block. # For example: # # %h1 foo # - with_tabs(2) do # %p bar # %strong baz # # Produces: # #

    foo

    #

    bar

    # baz # # # @param i [Fixnum] The number of tabs to use # @yield A block in which the indentation will be `i` spaces def with_tabs(i) old_tabs = haml_buffer.tabulation haml_buffer.tabulation = i yield ensure haml_buffer.tabulation = old_tabs end # Surrounds a block of Haml code with strings, # with no whitespace in between. # For example: # # = surround '(', ')' do # %a{:href => "food"} chicken # # Produces: # # (chicken) # # and # # = surround '*' do # %strong angry # # Produces: # # *angry* # # @param front [String] The string to add before the Haml # @param back [String] The string to add after the Haml # @yield A block of Haml to surround def surround(front, back = front, &block) output = capture_haml(&block) "#{front}#{output.chomp}#{back}\n" end # Prepends a string to the beginning of a Haml block, # with no whitespace between. # For example: # # = precede '*' do # %span.small Not really # # Produces: # # *Not really # # @param str [String] The string to add before the Haml # @yield A block of Haml to prepend to def precede(str, &block) "#{str}#{capture_haml(&block).chomp}\n" end # Appends a string to the end of a Haml block, # with no whitespace between. # For example: # # click # = succeed '.' do # %a{:href=>"thing"} here # # Produces: # # click # here. # # @param str [String] The string to add after the Haml # @yield A block of Haml to append to def succeed(str, &block) "#{capture_haml(&block).chomp}#{str}\n" end # Captures the result of a block of Haml code, # gets rid of the excess indentation, # and returns it as a string. # For example, after the following, # # .foo # - foo = capture_haml(13) do |a| # %p= a # # the local variable `foo` would be assigned to `"

    13

    \n"`. # # @param args [Array] Arguments to pass into the block # @yield [args] A block of Haml code that will be converted to a string # @yieldparam args [Array] `args` def capture_haml(*args, &block) buffer = eval('if defined? _hamlout then _hamlout else nil end', block.binding) || haml_buffer with_haml_buffer(buffer) do position = haml_buffer.buffer.length haml_buffer.capture_position = position value = block.call(*args) captured = haml_buffer.buffer.slice!(position..-1) if captured == '' and value != haml_buffer.buffer captured = (value.is_a?(String) ? value : nil) end captured end ensure haml_buffer.capture_position = nil end # Outputs text directly to the Haml buffer, with the proper indentation. # # @param text [#to_s] The text to output def haml_concat(text = "") haml_internal_concat text ErrorReturn.new("haml_concat") end # Internal method to write directly to the buffer with control of # whether the first line should be indented, and if there should be a # final newline. # # Lines added will have the proper indentation. This can be controlled # for the first line. # # Used by #haml_concat and #haml_tag. # # @param text [#to_s] The text to output # @param newline [Boolean] Whether to add a newline after the text # @param indent [Boolean] Whether to add indentation to the first line def haml_internal_concat(text = "", newline = true, indent = true) if haml_buffer.tabulation == 0 haml_buffer.buffer << "#{text}#{"\n" if newline}" else haml_buffer.buffer << %[#{haml_indent if indent}#{text.to_s.gsub("\n", "\n#{haml_indent}")}#{"\n" if newline}] end end private :haml_internal_concat # Allows writing raw content. `haml_internal_concat_raw` isn't # effected by XSS mods. Used by #haml_tag to write the actual tags. alias :haml_internal_concat_raw :haml_internal_concat # @return [String] The indentation string for the current line def haml_indent ' ' * haml_buffer.tabulation end # Creates an HTML tag with the given name and optionally text and attributes. # Can take a block that will run between the opening and closing tags. # If the block is a Haml block or outputs text using \{#haml\_concat}, # the text will be properly indented. # # `name` can be a string using the standard Haml class/id shorthand # (e.g. "span#foo.bar", "#foo"). # Just like standard Haml tags, these class and id values # will be merged with manually-specified attributes. # # `flags` is a list of symbol flags # like those that can be put at the end of a Haml tag # (`:/`, `:<`, and `:>`). # Currently, only `:/` and `:<` are supported. # # `haml_tag` outputs directly to the buffer; # its return value should not be used. # If you need to get the results as a string, # use \{#capture\_haml\}. # # For example, # # haml_tag :table do # haml_tag :tr do # haml_tag 'td.cell' do # haml_tag :strong, "strong!" # haml_concat "data" # end # haml_tag :td do # haml_concat "more_data" # end # end # end # # outputs # # # # # # #
    # # strong! # # data # # more_data #
    # # @param name [#to_s] The name of the tag # # @overload haml_tag(name, *rest, attributes = {}) # @yield The block of Haml code within the tag # @overload haml_tag(name, text, *flags, attributes = {}) # @param text [#to_s] The text within the tag # @param flags [Array] Haml end-of-tag flags def haml_tag(name, *rest, &block) ret = ErrorReturn.new("haml_tag") text = rest.shift.to_s unless [Symbol, Hash, NilClass].any? {|t| rest.first.is_a? t} flags = [] flags << rest.shift while rest.first.is_a? Symbol attrs = (rest.shift || {}) attrs.keys.each {|key| attrs[key.to_s] = attrs.delete(key)} unless attrs.empty? name, attrs = merge_name_and_attributes(name.to_s, attrs) attributes = Haml::AttributeBuilder.build_attributes(haml_buffer.html?, haml_buffer.options[:attr_wrapper], haml_buffer.options[:escape_attrs], haml_buffer.options[:hyphenate_data_attrs], attrs) if text.nil? && block.nil? && (haml_buffer.options[:autoclose].include?(name) || flags.include?(:/)) haml_internal_concat_raw "<#{name}#{attributes}#{' /' if haml_buffer.options[:format] == :xhtml}>" return ret end if flags.include?(:/) raise Error.new(Error.message(:self_closing_content)) if text raise Error.new(Error.message(:illegal_nesting_self_closing)) if block end tag = "<#{name}#{attributes}>" end_tag = "" if block.nil? text = text.to_s if text.include?("\n") haml_internal_concat_raw tag tab_up haml_internal_concat text tab_down haml_internal_concat_raw end_tag else haml_internal_concat_raw tag, false haml_internal_concat text, false, false haml_internal_concat_raw end_tag, true, false end return ret end if text raise Error.new(Error.message(:illegal_nesting_line, name)) end if flags.include?(:<) haml_internal_concat_raw tag, false haml_internal_concat "#{capture_haml(&block).strip}", false, false haml_internal_concat_raw end_tag, true, false return ret end haml_internal_concat_raw tag tab_up block.call tab_down haml_internal_concat_raw end_tag ret end # Conditionally wrap a block in an element. If `condition` is `true` then # this method renders the tag described by the arguments in `tag` (using # \{#haml_tag}) with the given block inside, otherwise it just renders the block. # # For example, # # - haml_tag_if important, '.important' do # %p # A (possibly) important paragraph. # # will produce # #
    #

    # A (possibly) important paragraph. #

    #
    # # if `important` is truthy, and just # #

    # A (possibly) important paragraph. #

    # # otherwise. # # Like \{#haml_tag}, `haml_tag_if` outputs directly to the buffer and its # return value should not be used. Use \{#capture_haml} if you need to use # its results as a string. # # @param condition The condition to test to determine whether to render # the enclosing tag # @param tag Definition of the enclosing tag. See \{#haml_tag} for details # (specifically the form that takes a block) def haml_tag_if(condition, *tag) if condition haml_tag(*tag){ yield } else yield end ErrorReturn.new("haml_tag_if") end # Characters that need to be escaped to HTML entities from user input HTML_ESCAPE = {'&' => '&', '<' => '<', '>' => '>', '"' => '"', "'" => '''}.freeze HTML_ESCAPE_REGEX = /['"><&]/ # Returns a copy of `text` with ampersands, angle brackets and quotes # escaped into HTML entities. # # Note that if ActionView is loaded and XSS protection is enabled # (as is the default for Rails 3.0+, and optional for version 2.3.5+), # this won't escape text declared as "safe". # # @param text [String] The string to sanitize # @return [String] The sanitized string def html_escape(text) ERB::Util.html_escape(text) end HTML_ESCAPE_ONCE_REGEX = /['"><]|&(?!(?:[a-zA-Z]+|#(?:\d+|[xX][0-9a-fA-F]+));)/ # Escapes HTML entities in `text`, but without escaping an ampersand # that is already part of an escaped entity. # # @param text [String] The string to sanitize # @return [String] The sanitized string def escape_once(text) text = text.to_s text.gsub(HTML_ESCAPE_ONCE_REGEX, HTML_ESCAPE) end # Returns whether or not the current template is a Haml template. # # This function, unlike other {Haml::Helpers} functions, # also works in other `ActionView` templates, # where it will always return false. # # @return [Boolean] Whether or not the current template is a Haml template def is_haml? !@haml_buffer.nil? && @haml_buffer.active? end # Returns whether or not `block` is defined directly in a Haml template. # # @param block [Proc] A Ruby block # @return [Boolean] Whether or not `block` is defined directly in a Haml template def block_is_haml?(block) eval('!!defined?(_hamlout)', block.binding) end private # Parses the tag name used for \{#haml\_tag} # and merges it with the Ruby attributes hash. def merge_name_and_attributes(name, attributes_hash = {}) # skip merging if no ids or classes found in name return name, attributes_hash unless name =~ /^(.+?)?([\.#].*)$/ return $1 || "div", AttributeBuilder.merge_attributes!( Haml::Parser.parse_class_and_id($2), attributes_hash) end # Runs a block of code with the given buffer as the currently active buffer. # # @param buffer [Haml::Buffer] The Haml buffer to use temporarily # @yield A block in which the given buffer should be used def with_haml_buffer(buffer) @haml_buffer, old_buffer = buffer, @haml_buffer old_buffer.active, old_was_active = false, old_buffer.active? if old_buffer @haml_buffer.active, was_active = true, @haml_buffer.active? yield ensure @haml_buffer.active = was_active old_buffer.active = old_was_active if old_buffer @haml_buffer = old_buffer end # The current {Haml::Buffer} object. # # @return [Haml::Buffer] def haml_buffer @haml_buffer if defined? @haml_buffer end # Gives a proc the same local `_hamlout` and `_erbout` variables # that the current template has. # # @param proc [#call] The proc to bind # @return [Proc] A new proc with the new variables bound def haml_bind_proc(&proc) _hamlout = haml_buffer #double assignment is to avoid warnings _erbout = _erbout = _hamlout.buffer proc { |*args| proc.call(*args) } end end end # @private class Object # Haml overrides various `ActionView` helpers, # which call an \{#is\_haml?} method # to determine whether or not the current context object # is a proper Haml context. # Because `ActionView` helpers may be included in non-`ActionView::Base` classes, # it's a good idea to define \{#is\_haml?} for all objects. def is_haml? false end end haml-5.1.2/lib/haml/helpers/000077500000000000000000000000001352226600500155725ustar00rootroot00000000000000haml-5.1.2/lib/haml/helpers/action_view_extensions.rb000066400000000000000000000037321352226600500227120ustar00rootroot00000000000000# frozen_string_literal: true module Haml module Helpers @@action_view_defined = true # This module contains various useful helper methods # that either tie into ActionView or the rest of the ActionPack stack, # or are only useful in that context. # Thus, the methods defined here are only available # if ActionView is installed. module ActionViewExtensions # Returns a value for the "class" attribute # unique to this controller/action pair. # This can be used to target styles specifically at this action or controller. # For example, if the current action were `EntryController#show`, # # %div{:class => page_class} My Div # # would become # #
    My Div
    # # Then, in a stylesheet (shown here as [Sass](http://sass-lang.com)), # you could refer to this specific action: # # .entry.show # font-weight: bold # # or to all actions in the entry controller: # # .entry # color: #00f # # @return [String] The class name for the current page def page_class "#{controller.controller_name} #{controller.action_name}" end alias_method :generate_content_class_names, :page_class # Treats all input to \{Haml::Helpers#haml\_concat} within the block # as being HTML safe for Rails' XSS protection. # This is useful for wrapping blocks of code that concatenate HTML en masse. # # This has no effect if Rails' XSS protection isn't enabled. # # @yield A block in which all input to `#haml_concat` is treated as raw. # @see Haml::Util#rails_xss_safe? def with_raw_haml_concat old = instance_variable_defined?(:@_haml_concat_raw) ? @_haml_concat_raw : false @_haml_concat_raw = true yield ensure @_haml_concat_raw = old end end include ActionViewExtensions end end haml-5.1.2/lib/haml/helpers/action_view_mods.rb000066400000000000000000000075301352226600500214550ustar00rootroot00000000000000# frozen_string_literal: true module Haml module Helpers module ActionViewMods def render(*args, &block) options = args.first # If render :layout is used with a block, it concats rather than returning # a string so we need it to keep thinking it's Haml until it hits the # sub-render. if is_haml? && !(options.is_a?(Hash) && options[:layout] && block_given?) return non_haml { super } end super end def output_buffer return haml_buffer.buffer if is_haml? super end def output_buffer=(new_buffer) if is_haml? if Haml::Util.rails_xss_safe? && new_buffer.is_a?(ActiveSupport::SafeBuffer) new_buffer = String.new(new_buffer) end haml_buffer.buffer = new_buffer else super end end end ActionView::Base.send(:prepend, ActionViewMods) end end module ActionView module Helpers module CaptureHelper def capture_with_haml(*args, &block) if Haml::Helpers.block_is_haml?(block) #double assignment is to avoid warnings _hamlout = _hamlout = eval('_hamlout', block.binding) # Necessary since capture_haml checks _hamlout capture_haml(*args, &block) else capture_without_haml(*args, &block) end end alias_method :capture_without_haml, :capture alias_method :capture, :capture_with_haml end module TagHelper DEFAULT_PRESERVE_OPTIONS = %w(textarea pre code).freeze def content_tag_with_haml(name, *args, &block) return content_tag_without_haml(name, *args, &block) unless is_haml? preserve = haml_buffer.options.fetch(:preserve, DEFAULT_PRESERVE_OPTIONS).include?(name.to_s) if block_given? && block_is_haml?(block) && preserve return content_tag_without_haml(name, *args) do haml_buffer.fix_textareas!(Haml::Helpers.preserve(&block)).html_safe end end content = content_tag_without_haml(name, *args, &block) if preserve && content content = haml_buffer.fix_textareas!(Haml::Helpers.preserve(content)).html_safe end content end alias_method :content_tag_without_haml, :content_tag alias_method :content_tag, :content_tag_with_haml end module HamlSupport include Haml::Helpers def haml_buffer @template_object.send :haml_buffer end def is_haml? @template_object.send :is_haml? end end module Tags class TextArea include HamlSupport end end class InstanceTag include HamlSupport def content_tag(*args, &block) html_tag = content_tag_with_haml(*args, &block) return html_tag unless respond_to?(:error_wrapping) return error_wrapping(html_tag) if method(:error_wrapping).arity == 1 return html_tag unless object.respond_to?(:errors) && object.errors.respond_to?(:on) return error_wrapping(html_tag, object.errors.on(@method_name)) end end module FormTagHelper def form_tag_with_haml(url_for_options = {}, options = {}, *parameters_for_url, &proc) if is_haml? wrap_block = block_given? && block_is_haml?(proc) if wrap_block oldproc = proc proc = haml_bind_proc do |*args| concat "\n" with_tabs(1) {oldproc.call(*args)} end end res = form_tag_without_haml(url_for_options, options, *parameters_for_url, &proc) << "\n" res << "\n" if wrap_block res else form_tag_without_haml(url_for_options, options, *parameters_for_url, &proc) end end alias_method :form_tag_without_haml, :form_tag alias_method :form_tag, :form_tag_with_haml end end end haml-5.1.2/lib/haml/helpers/action_view_xss_mods.rb000066400000000000000000000035051352226600500223500ustar00rootroot00000000000000# frozen_string_literal: true module ActionView module Helpers module CaptureHelper def with_output_buffer_with_haml_xss(*args, &block) res = with_output_buffer_without_haml_xss(*args, &block) case res when Array; res.map {|s| Haml::Util.html_safe(s)} when String; Haml::Util.html_safe(res) else; res end end alias_method :with_output_buffer_without_haml_xss, :with_output_buffer alias_method :with_output_buffer, :with_output_buffer_with_haml_xss end module FormTagHelper def form_tag_with_haml_xss(*args, &block) res = form_tag_without_haml_xss(*args, &block) res = Haml::Util.html_safe(res) unless block_given? res end alias_method :form_tag_without_haml_xss, :form_tag alias_method :form_tag, :form_tag_with_haml_xss end module FormHelper def form_for_with_haml_xss(*args, &block) res = form_for_without_haml_xss(*args, &block) return Haml::Util.html_safe(res) if res.is_a?(String) return res end alias_method :form_for_without_haml_xss, :form_for alias_method :form_for, :form_for_with_haml_xss end module TextHelper def concat_with_haml_xss(string) if is_haml? haml_buffer.buffer.concat(haml_xss_html_escape(string)) else concat_without_haml_xss(string) end end alias_method :concat_without_haml_xss, :concat alias_method :concat, :concat_with_haml_xss def safe_concat_with_haml_xss(string) if is_haml? haml_buffer.buffer.concat(string) else safe_concat_without_haml_xss(string) end end alias_method :safe_concat_without_haml_xss, :safe_concat alias_method :safe_concat, :safe_concat_with_haml_xss end end end haml-5.1.2/lib/haml/helpers/safe_erubi_template.rb000066400000000000000000000006001352226600500221120ustar00rootroot00000000000000# frozen_string_literal: true require 'action_view' module Haml class ErubiTemplateHandler < ActionView::Template::Handlers::ERB::Erubi def initialize(*args, &blk) @newline_pending = 0 super end end class SafeErubiTemplate < Tilt::ErubiTemplate def prepare @options.merge! engine_class: Haml::ErubiTemplateHandler super end end end haml-5.1.2/lib/haml/helpers/safe_erubis_template.rb000066400000000000000000000012001352226600500222720ustar00rootroot00000000000000# frozen_string_literal: true require 'action_view' module Haml class ErubisTemplateHandler < ActionView::Template::Handlers::Erubis def initialize(*args, &blk) @newline_pending = 0 super end end class SafeErubisTemplate < Tilt::ErubisTemplate def initialize_engine end def prepare @options.merge! :engine_class => Haml::ErubisTemplateHandler super end def precompiled_preamble(locals) [super, "@output_buffer = ActionView::OutputBuffer.new;"].join("\n") end def precompiled_postamble(locals) [super, '@output_buffer.to_s'].join("\n") end end end haml-5.1.2/lib/haml/helpers/xss_mods.rb000066400000000000000000000074221352226600500177630ustar00rootroot00000000000000# frozen_string_literal: true module Haml module Helpers # This module overrides Haml helpers to work properly # in the context of ActionView. # Currently it's only used for modifying the helpers # to work with Rails' XSS protection methods. module XssMods def self.included(base) %w[html_escape find_and_preserve preserve list_of surround precede succeed capture_haml haml_concat haml_internal_concat haml_indent escape_once].each do |name| base.send(:alias_method, "#{name}_without_haml_xss", name) base.send(:alias_method, name, "#{name}_with_haml_xss") end end # Don't escape text that's already safe, # output is always HTML safe def html_escape_with_haml_xss(text) str = text.to_s return text if str.html_safe? Haml::Util.html_safe(html_escape_without_haml_xss(str)) end # Output is always HTML safe def find_and_preserve_with_haml_xss(*args, &block) Haml::Util.html_safe(find_and_preserve_without_haml_xss(*args, &block)) end # Output is always HTML safe def preserve_with_haml_xss(*args, &block) Haml::Util.html_safe(preserve_without_haml_xss(*args, &block)) end # Output is always HTML safe def list_of_with_haml_xss(*args, &block) Haml::Util.html_safe(list_of_without_haml_xss(*args, &block)) end # Input is escaped, output is always HTML safe def surround_with_haml_xss(front, back = front, &block) Haml::Util.html_safe( surround_without_haml_xss( haml_xss_html_escape(front), haml_xss_html_escape(back), &block)) end # Input is escaped, output is always HTML safe def precede_with_haml_xss(str, &block) Haml::Util.html_safe(precede_without_haml_xss(haml_xss_html_escape(str), &block)) end # Input is escaped, output is always HTML safe def succeed_with_haml_xss(str, &block) Haml::Util.html_safe(succeed_without_haml_xss(haml_xss_html_escape(str), &block)) end # Output is always HTML safe def capture_haml_with_haml_xss(*args, &block) Haml::Util.html_safe(capture_haml_without_haml_xss(*args, &block)) end # Input will be escaped unless this is in a `with_raw_haml_concat` # block. See #Haml::Helpers::ActionViewExtensions#with_raw_haml_concat. def haml_concat_with_haml_xss(text = "") raw = instance_variable_defined?(:@_haml_concat_raw) ? @_haml_concat_raw : false if raw haml_internal_concat_raw text else haml_internal_concat text end ErrorReturn.new("haml_concat") end # Input is escaped def haml_internal_concat_with_haml_xss(text="", newline=true, indent=true) haml_internal_concat_without_haml_xss(haml_xss_html_escape(text), newline, indent) end private :haml_internal_concat_with_haml_xss # Output is always HTML safe def haml_indent_with_haml_xss Haml::Util.html_safe(haml_indent_without_haml_xss) end # Output is always HTML safe def escape_once_with_haml_xss(*args) Haml::Util.html_safe(escape_once_without_haml_xss(*args)) end private # Escapes the HTML in the text if and only if # Rails XSS protection is enabled *and* the `:escape_html` option is set. def haml_xss_html_escape(text) return text unless Haml::Util.rails_xss_safe? && haml_buffer.options[:escape_html] html_escape(text) end end class ErrorReturn # Any attempt to treat ErrorReturn as a string should cause it to blow up. alias_method :html_safe, :to_s alias_method :html_safe?, :to_s alias_method :html_safe!, :to_s end end end haml-5.1.2/lib/haml/options.rb000066400000000000000000000235171352226600500161600ustar00rootroot00000000000000# frozen_string_literal: true module Haml # This class encapsulates all of the configuration options that Haml # understands. Please see the {file:REFERENCE.md#options Haml Reference} to # learn how to set the options. class Options @valid_formats = [:html4, :html5, :xhtml] @buffer_option_keys = [:autoclose, :preserve, :attr_wrapper, :format, :encoding, :escape_html, :escape_filter_interpolations, :escape_attrs, :hyphenate_data_attrs, :cdata] class << self # The default option values. # @return Hash def defaults @defaults ||= Haml::TempleEngine.options.to_hash.merge(encoding: 'UTF-8') end # An array of valid values for the `:format` option. # @return Array attr_reader :valid_formats # An array of keys that will be used to provide a hash of options to # {Haml::Buffer}. # @return Hash attr_reader :buffer_option_keys # Returns a subset of defaults: those that {Haml::Buffer} cares about. # @return [{Symbol => Object}] The options hash def buffer_defaults @buffer_defaults ||= buffer_option_keys.inject({}) do |hash, key| hash.merge(key => defaults[key]) end end def wrap(options) if options.is_a?(Options) options else Options.new(options) end end end # The character that should wrap element attributes. This defaults to `'` # (an apostrophe). Characters of this type within the attributes will be # escaped (e.g. by replacing them with `'`) if the character is an # apostrophe or a quotation mark. attr_reader :attr_wrapper # A list of tag names that should be automatically self-closed if they have # no content. This can also contain regular expressions that match tag names # (or any object which responds to `#===`). Defaults to `['meta', 'img', # 'link', 'br', 'hr', 'input', 'area', 'param', 'col', 'base']`. attr_accessor :autoclose # The encoding to use for the HTML output. # This can be a string or an `Encoding` Object. Note that Haml **does not** # automatically re-encode Ruby values; any strings coming from outside the # application should be converted before being passed into the Haml # template. Defaults to `Encoding.default_internal`; if that's not set, # defaults to the encoding of the Haml template; if that's `US-ASCII`, # defaults to `"UTF-8"`. attr_reader :encoding # Sets whether or not to escape HTML-sensitive characters in attributes. If # this is true, all HTML-sensitive characters in attributes are escaped. If # it's set to false, no HTML-sensitive characters in attributes are escaped. # If it's set to `:once`, existing HTML escape sequences are preserved, but # other HTML-sensitive characters are escaped. # # Defaults to `true`. attr_accessor :escape_attrs # Sets whether or not to escape HTML-sensitive characters in script. If this # is true, `=` behaves like {file:REFERENCE.md#escaping_html `&=`}; # otherwise, it behaves like {file:REFERENCE.md#unescaping_html `!=`}. Note # that if this is set, `!=` should be used for yielding to subtemplates and # rendering partials. See also {file:REFERENCE.md#escaping_html Escaping HTML} and # {file:REFERENCE.md#unescaping_html Unescaping HTML}. # # Defaults to false. attr_accessor :escape_html # Sets whether or not to escape HTML-sensitive characters in interpolated strings. # See also {file:REFERENCE.md#escaping_html Escaping HTML} and # {file:REFERENCE.md#unescaping_html Unescaping HTML}. # # Defaults to the current value of `escape_html`. attr_accessor :escape_filter_interpolations # The name of the Haml file being parsed. # This is only used as information when exceptions are raised. This is # automatically assigned when working through ActionView, so it's really # only useful for the user to assign when dealing with Haml programatically. attr_accessor :filename # If set to `true`, Haml will convert underscores to hyphens in all # {file:REFERENCE.md#html5_custom_data_attributes Custom Data Attributes} As # of Haml 4.0, this defaults to `true`. attr_accessor :hyphenate_data_attrs # The line offset of the Haml template being parsed. This is useful for # inline templates, similar to the last argument to `Kernel#eval`. attr_accessor :line # Determines the output format. The default is `:html5`. The other options # are `:html4` and `:xhtml`. If the output is set to XHTML, then Haml # automatically generates self-closing tags and wraps the output of the # Javascript and CSS-like filters inside CDATA. When the output is set to # `:html5` or `:html4`, XML prologs are ignored. In all cases, an appropriate # doctype is generated from `!!!`. # # If the mime_type of the template being rendered is `text/xml` then a # format of `:xhtml` will be used even if the global output format is set to # `:html4` or `:html5`. attr :format # The mime type that the rendered document will be served with. If this is # set to `text/xml` then the format will be overridden to `:xhtml` even if # it has set to `:html4` or `:html5`. attr_accessor :mime_type # A list of tag names that should automatically have their newlines # preserved using the {Haml::Helpers#preserve} helper. This means that any # content given on the same line as the tag will be preserved. For example, # `%textarea= "Foo\nBar"` compiles to ``. # Defaults to `['textarea', 'pre']`. See also # {file:REFERENCE.md#whitespace_preservation Whitespace Preservation}. attr_accessor :preserve # If set to `true`, all tags are treated as if both # {file:REFERENCE.md#whitespace_removal__and_ whitespace removal} options # were present. Use with caution as this may cause whitespace-related # formatting errors. # # Defaults to `false`. attr_accessor :remove_whitespace # Whether or not attribute hashes and Ruby scripts designated by `=` or `~` # should be evaluated. If this is `true`, said scripts are rendered as empty # strings. # # Defaults to `false`. attr_accessor :suppress_eval # Whether to include CDATA sections around javascript and css blocks when # using the `:javascript` or `:css` filters. # # This option also affects the `:sass`, `:scss`, `:less` and `:coffeescript` # filters. # # Defaults to `false` for html, `true` for xhtml. Cannot be changed when using # xhtml. attr_accessor :cdata # The parser class to use. Defaults to Haml::Parser. attr_accessor :parser_class # The compiler class to use. Defaults to Haml::Compiler. attr_accessor :compiler_class # Enable template tracing. If true, it will add a 'data-trace' attribute to # each tag generated by Haml. The value of the attribute will be the # source template name and the line number from which the tag was generated, # separated by a colon. On Rails applications, the path given will be a # relative path as from the views directory. On non-Rails applications, # the path will be the full path. attr_accessor :trace # Key is filter name in String and value is Class to use. Defaults to {}. attr_accessor :filters def initialize(values = {}) defaults.each {|k, v| instance_variable_set :"@#{k}", v} values.each {|k, v| send("#{k}=", v) if defaults.has_key?(k) && !v.nil?} yield if block_given? end # Retrieve an option value. # @param key The value to retrieve. def [](key) send key end # Set an option value. # @param key The key to set. # @param value The value to set for the key. def []=(key, value) send "#{key}=", value end [:escape_attrs, :hyphenate_data_attrs, :remove_whitespace, :suppress_eval].each do |method| class_eval(<<-END) def #{method}? !! @#{method} end END end # @return [Boolean] Whether or not the format is XHTML. def xhtml? not html? end # @return [Boolean] Whether or not the format is any flavor of HTML. def html? html4? or html5? end # @return [Boolean] Whether or not the format is HTML4. def html4? format == :html4 end # @return [Boolean] Whether or not the format is HTML5. def html5? format == :html5 end def attr_wrapper=(value) @attr_wrapper = value || self.class.defaults[:attr_wrapper] end # Undef :format to suppress warning. It's defined above with the `:attr` # macro in order to make it appear in Yard's list of instance attributes. undef :format def format mime_type == "text/xml" ? :xhtml : @format end def format=(value) unless self.class.valid_formats.include?(value) raise Haml::Error, "Invalid output format #{value.inspect}" end @format = value end undef :cdata def cdata xhtml? || @cdata end def encoding=(value) return unless value @encoding = value.is_a?(Encoding) ? value.name : value.to_s @encoding = "UTF-8" if @encoding.upcase == "US-ASCII" end # Returns a non-default subset of options: those that {Haml::Buffer} cares about. # All of the values here are such that when `#inspect` is called on the hash, # it can be `Kernel#eval`ed to get the same result back. # # See {file:REFERENCE.md#options the Haml options documentation}. # # @return [{Symbol => Object}] The options hash def for_buffer self.class.buffer_option_keys.inject({}) do |hash, key| value = public_send(key) if self.class.buffer_defaults[key] != value hash[key] = value end hash end end private def defaults self.class.defaults end end end haml-5.1.2/lib/haml/parser.rb000066400000000000000000000661551352226600500157660ustar00rootroot00000000000000# frozen_string_literal: true require 'strscan' module Haml class Parser include Haml::Util attr_reader :root # Designates an XHTML/XML element. ELEMENT = ?% # Designates a `
    ` element with the given class. DIV_CLASS = ?. # Designates a `
    ` element with the given id. DIV_ID = ?# # Designates an XHTML/XML comment. COMMENT = ?/ # Designates an XHTML doctype or script that is never HTML-escaped. DOCTYPE = ?! # Designates script, the result of which is output. SCRIPT = ?= # Designates script that is always HTML-escaped. SANITIZE = ?& # Designates script, the result of which is flattened and output. FLAT_SCRIPT = ?~ # Designates script which is run but not output. SILENT_SCRIPT = ?- # When following SILENT_SCRIPT, designates a comment that is not output. SILENT_COMMENT = ?# # Designates a non-parsed line. ESCAPE = ?\\ # Designates a block of filtered text. FILTER = ?: # Designates a non-parsed line. Not actually a character. PLAIN_TEXT = -1 # Keeps track of the ASCII values of the characters that begin a # specially-interpreted line. SPECIAL_CHARACTERS = [ ELEMENT, DIV_CLASS, DIV_ID, COMMENT, DOCTYPE, SCRIPT, SANITIZE, FLAT_SCRIPT, SILENT_SCRIPT, ESCAPE, FILTER ].freeze # The value of the character that designates that a line is part # of a multiline string. MULTILINE_CHAR_VALUE = ?| # Regex to check for blocks with spaces around arguments. Not to be confused # with multiline script. # For example: # foo.each do | bar | # = bar # BLOCK_WITH_SPACES = /do\s*\|\s*[^\|]*\s+\|\z/ MID_BLOCK_KEYWORDS = %w[else elsif rescue ensure end when].freeze START_BLOCK_KEYWORDS = %w[if begin case unless].freeze # Try to parse assignments to block starters as best as possible START_BLOCK_KEYWORD_REGEX = /(?:\w+(?:,\s*\w+)*\s*=\s*)?(#{START_BLOCK_KEYWORDS.join('|')})/ BLOCK_KEYWORD_REGEX = /^-?\s*(?:(#{MID_BLOCK_KEYWORDS.join('|')})|#{START_BLOCK_KEYWORD_REGEX.source})\b/ # The Regex that matches a Doctype command. DOCTYPE_REGEX = /(\d(?:\.\d)?)?\s*([a-z]*)\s*([^ ]+)?/i # The Regex that matches a literal string or symbol value LITERAL_VALUE_REGEX = /:(\w*)|(["'])((?!\\|\#\{|\#@|\#\$|\2).|\\.)*\2/ ID_KEY = 'id'.freeze CLASS_KEY = 'class'.freeze def initialize(options) @options = Options.wrap(options) # Record the indent levels of "if" statements to validate the subsequent # elsif and else statements are indented at the appropriate level. @script_level_stack = [] @template_index = 0 @template_tabs = 0 end def call(template) match = template.rstrip.scan(/(([ \t]+)?(.*?))(?:\Z|\r\n|\r|\n)/m) # discard the last match which is always blank match.pop @template = match.each_with_index.map do |(full, whitespace, text), index| Line.new(whitespace, text.rstrip, full, index, self, false) end # Append special end-of-document marker @template << Line.new(nil, '-#', '-#', @template.size, self, true) @root = @parent = ParseNode.new(:root) @flat = false @filter_buffer = nil @indentation = nil @line = next_line raise SyntaxError.new(Error.message(:indenting_at_start), @line.index) if @line.tabs != 0 loop do next_line process_indent(@line) unless @line.text.empty? if flat? text = @line.full.dup text = "" unless text.gsub!(/^#{@flat_spaces}/, '') @filter_buffer << "#{text}\n" @line = @next_line next end @tab_up = nil process_line(@line) unless @line.text.empty? if block_opened? || @tab_up @template_tabs += 1 @parent = @parent.children.last end if !flat? && @next_line.tabs - @line.tabs > 1 raise SyntaxError.new(Error.message(:deeper_indenting, @next_line.tabs - @line.tabs), @next_line.index) end @line = @next_line end # Close all the open tags close until @parent.type == :root @root rescue Haml::Error => e e.backtrace.unshift "#{@options.filename}:#{(e.line ? e.line + 1 : @line.index + 1) + @options.line - 1}" raise end def compute_tabs(line) return 0 if line.text.empty? || !line.whitespace if @indentation.nil? @indentation = line.whitespace if @indentation.include?(?\s) && @indentation.include?(?\t) raise SyntaxError.new(Error.message(:cant_use_tabs_and_spaces), line.index) end @flat_spaces = @indentation * (@template_tabs+1) if flat? return 1 end tabs = line.whitespace.length / @indentation.length return tabs if line.whitespace == @indentation * tabs return @template_tabs + 1 if flat? && line.whitespace =~ /^#{@flat_spaces}/ message = Error.message(:inconsistent_indentation, human_indentation(line.whitespace), human_indentation(@indentation) ) raise SyntaxError.new(message, line.index) end private # @private Line = Struct.new(:whitespace, :text, :full, :index, :parser, :eod) do alias_method :eod?, :eod # @private def tabs @tabs ||= parser.compute_tabs(self) end def strip!(from) self.text = text[from..-1] self.text.lstrip! self end end # @private ParseNode = Struct.new(:type, :line, :value, :parent, :children) do def initialize(*args) super self.children ||= [] end def inspect %Q[(#{type} #{value.inspect}#{children.each_with_object(''.dup) {|c, s| s << "\n#{c.inspect.gsub!(/^/, ' ')}"}})].dup end end # @param [String] new - Hash literal including dynamic values. # @param [String] old - Hash literal including dynamic values or Ruby literal of multiple Hashes which MUST be interpreted as method's last arguments. DynamicAttributes = Struct.new(:new, :old) do undef :old= def old=(value) unless value =~ /\A{.*}\z/m raise ArgumentError.new('Old attributes must start with "{" and end with "}"') end self[:old] = value end # This will be a literal for Haml::Buffer#attributes's last argument, `attributes_hashes`. def to_literal [new, stripped_old].compact.join(', ') end private # For `%foo{ { foo: 1 }, bar: 2 }`, :old is "{ { foo: 1 }, bar: 2 }" and this method returns " { foo: 1 }, bar: 2 " for last argument. def stripped_old return nil if old.nil? old.sub!(/\A{/, '').sub!(/}\z/m, '') end end # Processes and deals with lowering indentation. def process_indent(line) return unless line.tabs <= @template_tabs && @template_tabs > 0 to_close = @template_tabs - line.tabs to_close.times {|i| close unless to_close - 1 - i == 0 && continuation_script?(line.text)} end def continuation_script?(text) text[0] == SILENT_SCRIPT && mid_block_keyword?(text) end def mid_block_keyword?(text) MID_BLOCK_KEYWORDS.include?(block_keyword(text)) end # Processes a single line of Haml. # # This method doesn't return anything; it simply processes the line and # adds the appropriate code to `@precompiled`. def process_line(line) case line.text[0] when DIV_CLASS; push div(line) when DIV_ID return push plain(line) if %w[{ @ $].include?(line.text[1]) push div(line) when ELEMENT; push tag(line) when COMMENT; push comment(line.text[1..-1].lstrip) when SANITIZE return push plain(line.strip!(3), :escape_html) if line.text[1, 2] == '==' return push script(line.strip!(2), :escape_html) if line.text[1] == SCRIPT return push flat_script(line.strip!(2), :escape_html) if line.text[1] == FLAT_SCRIPT return push plain(line.strip!(1), :escape_html) if line.text[1] == ?\s || line.text[1..2] == '#{' push plain(line) when SCRIPT return push plain(line.strip!(2)) if line.text[1] == SCRIPT line.text = line.text[1..-1] push script(line) when FLAT_SCRIPT; push flat_script(line.strip!(1)) when SILENT_SCRIPT return push haml_comment(line.text[2..-1]) if line.text[1] == SILENT_COMMENT push silent_script(line) when FILTER; push filter(line.text[1..-1].downcase) when DOCTYPE return push doctype(line.text) if line.text[0, 3] == '!!!' return push plain(line.strip!(3), false) if line.text[1, 2] == '==' return push script(line.strip!(2), false) if line.text[1] == SCRIPT return push flat_script(line.strip!(2), false) if line.text[1] == FLAT_SCRIPT return push plain(line.strip!(1), false) if line.text[1] == ?\s || line.text[1..2] == '#{' push plain(line) when ESCAPE line.text = line.text[1..-1] push plain(line) else; push plain(line) end end def block_keyword(text) return unless (keyword = text.scan(BLOCK_KEYWORD_REGEX)[0]) keyword[0] || keyword[1] end def push(node) @parent.children << node node.parent = @parent end def plain(line, escape_html = nil) if block_opened? raise SyntaxError.new(Error.message(:illegal_nesting_plain), @next_line.index) end unless contains_interpolation?(line.text) return ParseNode.new(:plain, line.index + 1, :text => line.text) end escape_html = @options.escape_html if escape_html.nil? line.text = unescape_interpolation(line.text, escape_html) script(line, false) end def script(line, escape_html = nil, preserve = false) raise SyntaxError.new(Error.message(:no_ruby_code, '=')) if line.text.empty? line = handle_ruby_multiline(line) escape_html = @options.escape_html if escape_html.nil? keyword = block_keyword(line.text) check_push_script_stack(keyword) ParseNode.new(:script, line.index + 1, :text => line.text, :escape_html => escape_html, :preserve => preserve, :keyword => keyword) end def flat_script(line, escape_html = nil) raise SyntaxError.new(Error.message(:no_ruby_code, '~')) if line.text.empty? script(line, escape_html, :preserve) end def silent_script(line) raise SyntaxError.new(Error.message(:no_end), line.index) if line.text[1..-1].strip == 'end' line = handle_ruby_multiline(line) keyword = block_keyword(line.text) check_push_script_stack(keyword) if ["else", "elsif", "when"].include?(keyword) if @script_level_stack.empty? raise Haml::SyntaxError.new(Error.message(:missing_if, keyword), @line.index) end if keyword == 'when' and !@script_level_stack.last[2] if @script_level_stack.last[1] + 1 == @line.tabs @script_level_stack.last[1] += 1 end @script_level_stack.last[2] = true end if @script_level_stack.last[1] != @line.tabs message = Error.message(:bad_script_indent, keyword, @script_level_stack.last[1], @line.tabs) raise Haml::SyntaxError.new(message, @line.index) end end ParseNode.new(:silent_script, @line.index + 1, :text => line.text[1..-1], :keyword => keyword) end def check_push_script_stack(keyword) if ["if", "case", "unless"].include?(keyword) # @script_level_stack contents are arrays of form # [:keyword, stack_level, other_info] @script_level_stack.push([keyword.to_sym, @line.tabs]) @script_level_stack.last << false if keyword == 'case' @tab_up = true end end def haml_comment(text) if filter_opened? @flat = true @filter_buffer = String.new @filter_buffer << "#{text}\n" unless text.empty? text = @filter_buffer # If we don't know the indentation by now, it'll be set in Line#tabs @flat_spaces = @indentation * (@template_tabs+1) if @indentation end ParseNode.new(:haml_comment, @line.index + 1, :text => text) end def tag(line) tag_name, attributes, attributes_hashes, object_ref, nuke_outer_whitespace, nuke_inner_whitespace, action, value, last_line = parse_tag(line.text) preserve_tag = @options.preserve.include?(tag_name) nuke_inner_whitespace ||= preserve_tag escape_html = (action == '&' || (action != '!' && @options.escape_html)) case action when '/'; self_closing = true when '~'; parse = preserve_script = true when '=' parse = true if value[0] == ?= value = unescape_interpolation(value[1..-1].strip, escape_html) escape_html = false end when '&', '!' if value[0] == ?= || value[0] == ?~ parse = true preserve_script = (value[0] == ?~) if value[1] == ?= value = unescape_interpolation(value[2..-1].strip, escape_html) escape_html = false else value = value[1..-1].strip end elsif contains_interpolation?(value) value = unescape_interpolation(value, escape_html) parse = true escape_html = false end else if contains_interpolation?(value) value = unescape_interpolation(value, escape_html) parse = true escape_html = false end end attributes = Parser.parse_class_and_id(attributes) dynamic_attributes = DynamicAttributes.new if attributes_hashes[:new] static_attributes, attributes_hash = attributes_hashes[:new] AttributeBuilder.merge_attributes!(attributes, static_attributes) if static_attributes dynamic_attributes.new = attributes_hash end if attributes_hashes[:old] static_attributes = parse_static_hash(attributes_hashes[:old]) AttributeBuilder.merge_attributes!(attributes, static_attributes) if static_attributes dynamic_attributes.old = attributes_hashes[:old] unless static_attributes || @options.suppress_eval end raise SyntaxError.new(Error.message(:illegal_nesting_self_closing), @next_line.index) if block_opened? && self_closing raise SyntaxError.new(Error.message(:no_ruby_code, action), last_line - 1) if parse && value.empty? raise SyntaxError.new(Error.message(:self_closing_content), last_line - 1) if self_closing && !value.empty? if block_opened? && !value.empty? && !is_ruby_multiline?(value) raise SyntaxError.new(Error.message(:illegal_nesting_line, tag_name), @next_line.index) end self_closing ||= !!(!block_opened? && value.empty? && @options.autoclose.any? {|t| t === tag_name}) value = nil if value.empty? && (block_opened? || self_closing) line.text = value line = handle_ruby_multiline(line) if parse ParseNode.new(:tag, line.index + 1, :name => tag_name, :attributes => attributes, :dynamic_attributes => dynamic_attributes, :self_closing => self_closing, :nuke_inner_whitespace => nuke_inner_whitespace, :nuke_outer_whitespace => nuke_outer_whitespace, :object_ref => object_ref, :escape_html => escape_html, :preserve_tag => preserve_tag, :preserve_script => preserve_script, :parse => parse, :value => line.text) end # Renders a line that creates an XHTML tag and has an implicit div because of # `.` or `#`. def div(line) line.text = "%div#{line.text}" tag(line) end # Renders an XHTML comment. def comment(text) if text[0..1] == '![' revealed = true text = text[1..-1] else revealed = false end conditional, text = balance(text, ?[, ?]) if text[0] == ?[ text.strip! if contains_interpolation?(text) parse = true text = unescape_interpolation(text) else parse = false end if block_opened? && !text.empty? raise SyntaxError.new(Haml::Error.message(:illegal_nesting_content), @next_line.index) end ParseNode.new(:comment, @line.index + 1, :conditional => conditional, :text => text, :revealed => revealed, :parse => parse) end # Renders an XHTML doctype or XML shebang. def doctype(text) raise SyntaxError.new(Error.message(:illegal_nesting_header), @next_line.index) if block_opened? version, type, encoding = text[3..-1].strip.downcase.scan(DOCTYPE_REGEX)[0] ParseNode.new(:doctype, @line.index + 1, :version => version, :type => type, :encoding => encoding) end def filter(name) raise Error.new(Error.message(:invalid_filter_name, name)) unless name =~ /^\w+$/ if filter_opened? @flat = true @filter_buffer = String.new # If we don't know the indentation by now, it'll be set in Line#tabs @flat_spaces = @indentation * (@template_tabs+1) if @indentation end ParseNode.new(:filter, @line.index + 1, :name => name, :text => @filter_buffer) end def close node, @parent = @parent, @parent.parent @template_tabs -= 1 send("close_#{node.type}", node) if respond_to?("close_#{node.type}", :include_private) end def close_filter(_) close_flat_section end def close_haml_comment(_) close_flat_section end def close_flat_section @flat = false @flat_spaces = nil @filter_buffer = nil end def close_silent_script(node) @script_level_stack.pop if ["if", "case", "unless"].include? node.value[:keyword] # Post-process case statements to normalize the nesting of "when" clauses return unless node.value[:keyword] == "case" return unless (first = node.children.first) return unless first.type == :silent_script && first.value[:keyword] == "when" return if first.children.empty? # If the case node has a "when" child with children, it's the # only child. Then we want to put everything nested beneath it # beneath the case itself (just like "if"). node.children = [first, *first.children] first.children = [] end alias :close_script :close_silent_script # This is a class method so it can be accessed from {Haml::Helpers}. # # Iterates through the classes and ids supplied through `.` # and `#` syntax, and returns a hash with them as attributes, # that can then be merged with another attributes hash. def self.parse_class_and_id(list) attributes = {} return attributes if list.empty? list.scan(/([#.])([-:_a-zA-Z0-9\@]+)/) do |type, property| case type when '.' if attributes[CLASS_KEY] attributes[CLASS_KEY] += " " else attributes[CLASS_KEY] = "" end attributes[CLASS_KEY] += property when '#'; attributes[ID_KEY] = property end end attributes end # This method doesn't use Haml::AttributeParser because currently it depends on Ripper and Rubinius doesn't provide it. # Ideally this logic should be placed in Haml::AttributeParser instead of here and this method should use it. # # @param [String] text - Hash literal or text inside old attributes # @return [Hash,nil] - Return nil if text is not static Hash literal def parse_static_hash(text) attributes = {} return attributes if text.empty? text = text[1...-1] # strip brackets scanner = StringScanner.new(text) scanner.scan(/\s+/) until scanner.eos? return unless (key = scanner.scan(LITERAL_VALUE_REGEX)) return unless scanner.scan(/\s*=>\s*/) return unless (value = scanner.scan(LITERAL_VALUE_REGEX)) return unless scanner.scan(/\s*(?:,|$)\s*/) attributes[eval(key).to_s] = eval(value).to_s end attributes end # Parses a line into tag_name, attributes, attributes_hash, object_ref, action, value def parse_tag(text) match = text.scan(/%([-:\w]+)([-:\w.#\@]*)(.+)?/)[0] raise SyntaxError.new(Error.message(:invalid_tag, text)) unless match tag_name, attributes, rest = match if !attributes.empty? && (attributes =~ /[.#](\.|#|\z)/) raise SyntaxError.new(Error.message(:illegal_element)) end new_attributes_hash = old_attributes_hash = last_line = nil object_ref = :nil attributes_hashes = {} while rest && !rest.empty? case rest[0] when ?{ break if old_attributes_hash old_attributes_hash, rest, last_line = parse_old_attributes(rest) attributes_hashes[:old] = old_attributes_hash when ?( break if new_attributes_hash new_attributes_hash, rest, last_line = parse_new_attributes(rest) attributes_hashes[:new] = new_attributes_hash when ?[ break unless object_ref == :nil object_ref, rest = balance(rest, ?[, ?]) else; break end end if rest && !rest.empty? nuke_whitespace, action, value = rest.scan(/(<>|><|[><])?([=\/\~&!])?(.*)?/)[0] if nuke_whitespace nuke_outer_whitespace = nuke_whitespace.include? '>' nuke_inner_whitespace = nuke_whitespace.include? '<' end end if @options.remove_whitespace nuke_outer_whitespace = true nuke_inner_whitespace = true end if value.nil? value = '' else value.strip! end [tag_name, attributes, attributes_hashes, object_ref, nuke_outer_whitespace, nuke_inner_whitespace, action, value, last_line || @line.index + 1] end # @return [String] attributes_hash - Hash literal starting with `{` and ending with `}` # @return [String] rest # @return [Integer] last_line def parse_old_attributes(text) text = text.dup last_line = @line.index + 1 begin attributes_hash, rest = balance(text, ?{, ?}) rescue SyntaxError => e if text.strip[-1] == ?, && e.message == Error.message(:unbalanced_brackets) text << "\n#{@next_line.text}" last_line += 1 next_line retry end raise e end return attributes_hash, rest, last_line end # @return [Array] - [static_attributes (Hash), dynamic_attributes (nil or String starting with `{` and ending with `}`)] # @return [String] rest # @return [Integer] last_line def parse_new_attributes(text) scanner = StringScanner.new(text) last_line = @line.index + 1 attributes = {} scanner.scan(/\(\s*/) loop do name, value = parse_new_attribute(scanner) break if name.nil? if name == false scanned = Haml::Util.balance(text, ?(, ?)) text = scanned ? scanned.first : text raise Haml::SyntaxError.new(Error.message(:invalid_attribute_list, text.inspect), last_line - 1) end attributes[name] = value scanner.scan(/\s*/) if scanner.eos? text << " #{@next_line.text}" last_line += 1 next_line scanner.scan(/\s*/) end end static_attributes = {} dynamic_attributes = "{".dup attributes.each do |name, (type, val)| if type == :static static_attributes[name] = val else dynamic_attributes << "#{inspect_obj(name)} => #{val}," end end dynamic_attributes << "}" dynamic_attributes = nil if dynamic_attributes == "{}" return [static_attributes, dynamic_attributes], scanner.rest, last_line end def parse_new_attribute(scanner) unless (name = scanner.scan(/[-:\w]+/)) return if scanner.scan(/\)/) return false end scanner.scan(/\s*/) return name, [:static, true] unless scanner.scan(/=/) #/end scanner.scan(/\s*/) unless (quote = scanner.scan(/["']/)) return false unless (var = scanner.scan(/(@@?|\$)?\w+/)) return name, [:dynamic, var] end re = /((?:\\.|\#(?!\{)|[^#{quote}\\#])*)(#{quote}|#\{)/ content = [] loop do return false unless scanner.scan(re) content << [:str, scanner[1].gsub(/\\(.)/, '\1')] break if scanner[2] == quote content << [:ruby, balance(scanner, ?{, ?}, 1).first[0...-1]] end return name, [:static, content.first[1]] if content.size == 1 return name, [:dynamic, %!"#{content.each_with_object(''.dup) {|(t, v), s| s << (t == :str ? inspect_obj(v)[1...-1] : "\#{#{v}}")}}"!] end def next_line line = @template.shift || raise(StopIteration) # `flat?' here is a little outdated, # so we have to manually check if either the previous or current line # closes the flat block, as well as whether a new block is opened. line_defined = instance_variable_defined?(:@line) @line.tabs if line_defined unless (flat? && !closes_flat?(line) && !closes_flat?(@line)) || (line_defined && @line.text[0] == ?: && line.full =~ %r[^#{@line.full[/^\s+/]}\s]) return next_line if line.text.empty? handle_multiline(line) end @next_line = line end def closes_flat?(line) line && !line.text.empty? && line.full !~ /^#{@flat_spaces}/ end def handle_multiline(line) return unless is_multiline?(line.text) line.text.slice!(-1) loop do new_line = @template.first break if new_line.eod? next @template.shift if new_line.text.strip.empty? break unless is_multiline?(new_line.text.strip) line.text << new_line.text.strip[0...-1] @template.shift end end # Checks whether or not `line` is in a multiline sequence. def is_multiline?(text) text && text.length > 1 && text[-1] == MULTILINE_CHAR_VALUE && text[-2] == ?\s && text !~ BLOCK_WITH_SPACES end def handle_ruby_multiline(line) line.text.rstrip! return line unless is_ruby_multiline?(line.text) begin # Use already fetched @next_line in the first loop. Otherwise, fetch next new_line = new_line.nil? ? @next_line : @template.shift break if new_line.eod? next if new_line.text.empty? line.text << " #{new_line.text.rstrip}" end while is_ruby_multiline?(new_line.text) next_line line end # `text' is a Ruby multiline block if it: # - ends with a comma # - but not "?," which is a character literal # (however, "x?," is a method call and not a literal) # - and not "?\," which is a character literal def is_ruby_multiline?(text) text && text.length > 1 && text[-1] == ?, && !((text[-3, 2] =~ /\W\?/) || text[-3, 2] == "?\\") end def balance(*args) Haml::Util.balance(*args) or raise(SyntaxError.new(Error.message(:unbalanced_brackets))) end def block_opened? @next_line.tabs > @line.tabs end # Same semantics as block_opened?, except that block_opened? uses Line#tabs, # which doesn't interact well with filter lines def filter_opened? @next_line.full =~ (@indentation ? /^#{@indentation * (@template_tabs + 1)}/ : /^\s/) end def flat? @flat end end end haml-5.1.2/lib/haml/plugin.rb000066400000000000000000000020731352226600500157550ustar00rootroot00000000000000# frozen_string_literal: true module Haml # This module makes Haml work with Rails using the template handler API. class Plugin def handles_encoding?; true; end def compile(template, source) options = Haml::Template.options.dup if template.respond_to?(:type) options[:mime_type] = template.type elsif template.respond_to? :mime_type options[:mime_type] = template.mime_type end options[:filename] = template.identifier Haml::Engine.new(source, options).compiler.precompiled_with_ambles( [], after_preamble: '@output_buffer = output_buffer ||= ActionView::OutputBuffer.new if defined?(ActionView::OutputBuffer)', ) end def self.call(template, source = nil) source ||= template.source new.compile(template, source) end def cache_fragment(block, name = {}, options = nil) @view.fragment_for(block, name, options) do eval("_hamlout.buffer", block.binding) end end end end ActionView::Template.register_template_handler(:haml, Haml::Plugin) haml-5.1.2/lib/haml/railtie.rb000066400000000000000000000034011352226600500161040ustar00rootroot00000000000000# frozen_string_literal: true require 'haml/template/options' # check for a compatible Rails version when Haml is loaded if (activesupport_spec = Gem.loaded_specs['activesupport']) if activesupport_spec.version.to_s < '4.0' raise Exception.new("\n\n** Haml now requires Rails 4.0 and later. Use Haml version 4.0.x\n\n") end end module Haml module Filters module RailsErb extend Plain extend TiltFilter extend PrecompiledTiltFilter end end class Railtie < ::Rails::Railtie initializer :haml do |app| ActiveSupport.on_load(:action_view) do require "haml/template" if defined?(::Sass::Rails::SassTemplate) && app.config.assets.enabled require "haml/sass_rails_filter" end # Any object under ActionView::Template will be defined as the root constant with the same # name if it exists. If Erubi is loaded at all, ActionView::Template::Handlers::ERB::Erubi # will turn out to be a reference to the ::Erubi module. # In Rails 4.2, calling const_defined? results in odd exceptions, which seems to be # solved by looking for ::Erubi first. # However, in JRuby, the const_defined? finds it anyway, so we must make sure that it's # not just a reference to ::Erubi. if defined?(::Erubi) && (::ActionView::Template::Handlers::ERB.const_get('Erubi') != ::Erubi) require "haml/helpers/safe_erubi_template" Haml::Filters::RailsErb.template_class = Haml::SafeErubiTemplate else require "haml/helpers/safe_erubis_template" Haml::Filters::RailsErb.template_class = Haml::SafeErubisTemplate end Haml::Template.options[:filters] = { 'erb' => Haml::Filters::RailsErb } end end end end haml-5.1.2/lib/haml/sass_rails_filter.rb000066400000000000000000000027641352226600500201760ustar00rootroot00000000000000# frozen_string_literal: true module Haml module Filters # This is an extension of Sass::Rails's SassTemplate class that allows # Rails's asset helpers to be used inside Haml Sass filter. class SassRailsTemplate < ::Sass::Rails::SassTemplate if Gem::Version.new(Sprockets::VERSION) >= Gem::Version.new('3.0.0') def render(scope=Object.new, locals={}, &block) environment = ::Sprockets::Railtie.build_environment(::Rails.application) scope = environment.context_class.new( environment: environment, filename: "/", metadata: {} ) super end else def render(scope=Object.new, locals={}, &block) scope = ::Rails.application.assets.context_class.new(::Rails.application.assets, "/", "/") super end end def sass_options(scope) options = super options[:custom][:resolver] = ::ActionView::Base.new options end end # This is an extension of Sass::Rails's SassTemplate class that allows # Rails's asset helpers to be used inside a Haml SCSS filter. class ScssRailsTemplate < SassRailsTemplate self.default_mime_type = 'text/css' def syntax :scss end end remove_filter :Sass remove_filter :Scss register_tilt_filter "Sass", :extend => "Css", :template_class => SassRailsTemplate register_tilt_filter "Scss", :extend => "Css", :template_class => ScssRailsTemplate end end haml-5.1.2/lib/haml/template.rb000066400000000000000000000020131352226600500162640ustar00rootroot00000000000000# frozen_string_literal: true require 'haml/template/options' if defined?(ActiveSupport) ActiveSupport.on_load(:action_view) do require 'haml/helpers/action_view_mods' require 'haml/helpers/action_view_extensions' end else require 'haml/helpers/action_view_mods' require 'haml/helpers/action_view_extensions' end require 'haml/helpers/xss_mods' require 'haml/helpers/action_view_xss_mods' module Haml class TempleEngine def precompiled_method_return_value_with_haml_xss "::Haml::Util.html_safe(#{precompiled_method_return_value_without_haml_xss})" end alias_method :precompiled_method_return_value_without_haml_xss, :precompiled_method_return_value alias_method :precompiled_method_return_value, :precompiled_method_return_value_with_haml_xss end module Helpers include Haml::Helpers::XssMods end module Util undef :rails_xss_safe? if defined? rails_xss_safe? def rails_xss_safe?; true; end end end Haml::Template.options[:escape_html] = true require 'haml/plugin' haml-5.1.2/lib/haml/template/000077500000000000000000000000001352226600500157435ustar00rootroot00000000000000haml-5.1.2/lib/haml/template/options.rb000066400000000000000000000012731352226600500177660ustar00rootroot00000000000000# frozen_string_literal: true # We keep options in its own self-contained file # so that we can load it independently in Rails 3, # where the full template stuff is lazy-loaded. module Haml module Template extend self class Options < Hash def []=(key, value) super if Haml::Options.buffer_defaults.key?(key) Haml::Options.buffer_defaults[key] = value end end end @options = ::Haml::Template::Options.new # The options hash for Haml when used within Rails. # See {file:REFERENCE.md#options the Haml options documentation}. # # @return [Haml::Template::Options Object>] attr_accessor :options end end haml-5.1.2/lib/haml/temple_engine.rb000066400000000000000000000072531352226600500172770ustar00rootroot00000000000000# frozen_string_literal: true require 'temple' require 'haml/escapable' require 'haml/generator' module Haml class TempleEngine < Temple::Engine define_options( attr_wrapper: "'", autoclose: %w(area base basefont br col command embed frame hr img input isindex keygen link menuitem meta param source track wbr), encoding: nil, escape_attrs: true, escape_html: false, escape_filter_interpolations: nil, filename: '(haml)', format: :html5, hyphenate_data_attrs: true, line: 1, mime_type: 'text/html', preserve: %w(textarea pre code), remove_whitespace: false, suppress_eval: false, cdata: false, parser_class: ::Haml::Parser, compiler_class: ::Haml::Compiler, trace: false, filters: {}, ) use :Parser, -> { options[:parser_class] } use :Compiler, -> { options[:compiler_class] } use Escapable filter :ControlFlow filter :MultiFlattener filter :StaticMerger use Generator def compile(template) initialize_encoding(template, options[:encoding]) @precompiled = call(template) end # The source code that is evaluated to produce the Haml document. # # This is automatically converted to the correct encoding # (see {file:REFERENCE.md#encodings the `:encoding` option}). # # @return [String] def precompiled encoding = Encoding.find(@encoding || '') return @precompiled.dup.force_encoding(encoding) if encoding == Encoding::ASCII_8BIT return @precompiled.encode(encoding) end def precompiled_with_return_value "#{precompiled};#{precompiled_method_return_value}".dup end # The source code that is evaluated to produce the Haml document. # # This is automatically converted to the correct encoding # (see {file:REFERENCE.md#encodings the `:encoding` option}). # # @return [String] def precompiled_with_ambles(local_names, after_preamble: '') preamble = < e yield < bar}') } it { assert_parse(nil, '{[] => bar}') } it { assert_parse(nil, '{[1,2,3] => bar}') } end describe 'foo: bar' do it { assert_parse({ '_' => '1' }, '{_:1,}') } it { assert_parse({ 'foo' => 'bar' }, '{ foo: bar }') } it { assert_parse({ 'a' => 'b', 'c' => ':d' }, '{a: b, c: :d}') } it { assert_parse({ 'a' => '[]', 'c' => '"d"' }, '{a: [], c: "d"}') } end describe ':foo => bar' do it { assert_parse({ 'foo' => ':bar' }, '{ :foo => :bar }') } it { assert_parse({ '_' => '"foo"' }, '{:_=>"foo"}') } it { assert_parse({ 'a' => '[]', 'c' => '""', 'b' => '"#{3}"' }, '{:a => [], c: "", :b => "#{3}"}') } it { assert_parse(nil, '{:"f#{o}o" => bar}') } it { assert_parse(nil, '{:"#{f}oo" => bar}') } it { assert_parse(nil, '{:"#{foo}" => bar}') } end describe '"foo" => bar' do it { assert_parse({ 'foo' => '[1]' }, '{"foo"=>[1]}') } it { assert_parse({ 'foo' => 'nya' }, "{ 'foo' => nya }") } it { assert_parse({ 'foo' => 'bar' }, '{%q[foo] => bar }') } it { assert_parse({ 'foo' => '[1]' }, ' { "foo"=>[1] } ') } it { assert_parse({ 'foo' => 'nya' }, " { 'foo' => nya } ") } it { assert_parse({ 'foo' => 'bar' }, ' { %q[foo] => bar } ') } it { assert_parse(nil, '{"f#{o}o" => bar}') } it { assert_parse(nil, '{"#{f}oo" => bar}') } it { assert_parse(nil, '{"#{foo}" => bar}') } it { assert_parse({ 'f#{o}o' => 'bar' }, '{ %q[f#{o}o] => bar }') } it { assert_parse({ 'f#{o}o' => 'bar' }, '{ %q[f#{o}o] => bar, }') } it { assert_parse(nil, '%Q[f#{o}o] => bar ') } end describe 'string interpolation' do it { assert_parse({ 'foo' => %q["#{bar baz, '/abc/'}"] }, %q[{foo: "#{bar baz, '/abc/'}"}]) } end describe 'multi lines' do it { assert_parse({ 'a' => 'b', 'c' => 'd' }, "{a: b,\nc: d}") } end if RUBY_VERSION >= '2.2.0' describe '"foo": bar' do it { assert_parse({ 'foo' => '()' }, '{"foo":()}') } it { assert_parse({ 'foo' => 'nya' }, " {'foo': nya} ") } it { assert_parse({ 'foo' => '()' }, ' { "foo":() , }') } it { assert_parse({ 'foo' => 'nya' }, " { 'foo': nya , }") } it { assert_parse(nil, '{"f#{o}o": bar}') } it { assert_parse(nil, '{"#{f}oo": bar}') } it { assert_parse(nil, '{"#{foo}": bar}') } end end describe 'nested array' do it { assert_parse({ 'foo' => '[1,2,]' }, '{foo: [1,2,],}') } it { assert_parse({ 'foo' => '[1,2,[3,4],5]' }, '{foo: [1,2,[3,4],5],}') } it { assert_parse({ 'foo' => '[1,2,[3,4],5]', 'bar' => '[[1,2],]'}, '{foo: [1,2,[3,4],5],bar: [[1,2],],}') } end describe 'nested hash' do it { assert_parse({ 'foo' => '{ }', 'bar' => '{}' }, '{foo: { }, bar: {}}') } it { assert_parse({ 'foo' => '{ bar: baz, hoge: fuga, }' }, '{foo: { bar: baz, hoge: fuga, }, }') } it { assert_parse({ 'data' => '{ confirm: true, disable: false }', 'hello' => '{ world: foo, }' }, '{data: { confirm: true, disable: false }, :hello => { world: foo, },}') } end describe 'nested method' do it { assert_parse({ 'foo' => 'bar(a, b)', 'hoge' => 'piyo(a, b,)' }, '{ foo: bar(a, b), hoge: piyo(a, b,), }') } end end end end haml-5.1.2/test/engine_test.rb000066400000000000000000002065251352226600500162630ustar00rootroot00000000000000# -*- coding: utf-8 -*- # frozen_string_literal: true require 'test_helper' class EngineTest < Haml::TestCase # A map of erroneous Haml documents to the error messages they should produce. # The error messages may be arrays; # if so, the second element should be the line number that should be reported for the error. # If this isn't provided, the tests will assume the line number should be the last line of the document. EXCEPTION_MAP = { "!!!\n a" => error(:illegal_nesting_header), "a\n b" => error(:illegal_nesting_plain), "/ a\n b" => error(:illegal_nesting_content), "% a" => error(:invalid_tag, '% a'), "%p a\n b" => error(:illegal_nesting_line, 'p'), "%p=" => error(:no_ruby_code, '='), "%p~" => error(:no_ruby_code, '~'), "~" => error(:no_ruby_code, '~'), "=" => error(:no_ruby_code, '='), "%p/\n a" => error(:illegal_nesting_self_closing), ":a\n b" => [error(:filter_not_defined, 'a'), 1], ":a= b" => error(:invalid_filter_name, 'a= b'), "." => error(:illegal_element), ".#" => error(:illegal_element), ".{} a" => error(:illegal_element), ".() a" => error(:illegal_element), ".= a" => error(:illegal_element), "%p..a" => error(:illegal_element), "%a/ b" => error(:self_closing_content), " %p foo" => error(:indenting_at_start), " %p foo" => error(:indenting_at_start), "- end" => error(:no_end), "%p{:a => 'b',\n:c => 'd'}/ e" => [error(:self_closing_content), 2], "%p{:a => 'b',\n:c => 'd'}=" => [error(:no_ruby_code, '='), 2], "%p.{:a => 'b',\n:c => 'd'} e" => [error(:illegal_element), 1], "%p{:a => 'b',\n:c => 'd',\n:e => 'f'}\n%p/ a" => [error(:self_closing_content), 4], "%p{:a => 'b',\n:c => 'd',\n:e => 'f'}\n- raise 'foo'" => ["foo", 4], "%p{:a => 'b',\n:c => raise('foo'),\n:e => 'f'}" => ["foo", 2], "%p{:a => 'b',\n:c => 'd',\n:e => raise('foo')}" => ["foo", 3], " \n\t\n %p foo" => [error(:indenting_at_start), 3], "\n\n %p foo" => [error(:indenting_at_start), 3], "%p\n foo\n foo" => [error(:inconsistent_indentation, "1 space", "2 spaces"), 3], "%p\n foo\n%p\n foo" => [error(:inconsistent_indentation, "1 space", "2 spaces"), 4], "%p\n\t\tfoo\n\tfoo" => [error(:inconsistent_indentation, "1 tab", "2 tabs"), 3], "%p\n foo\n foo" => [error(:inconsistent_indentation, "3 spaces", "2 spaces"), 3], "%p\n foo\n %p\n bar" => [error(:inconsistent_indentation, "3 spaces", "2 spaces"), 4], "%p\n :plain\n bar\n \t baz" => [error(:inconsistent_indentation, '" \t "', "2 spaces"), 4], "%p\n foo\n%p\n bar" => [error(:deeper_indenting, 2), 4], "%p\n foo\n %p\n bar" => [error(:deeper_indenting, 3), 4], "%p\n \tfoo" => [error(:cant_use_tabs_and_spaces), 2], "%p(" => error(:invalid_attribute_list, '"("'), "%p(foo=)" => error(:invalid_attribute_list, '"(foo=)"'), "%p(foo 'bar')" => error(:invalid_attribute_list, '"(foo \'bar\')"'), "%p(foo=\nbar)" => [error(:invalid_attribute_list, '"(foo="'), 1], "%p(foo 'bar'\nbaz='bang')" => [error(:invalid_attribute_list, '"(foo \'bar\'"'), 1], "%p(foo='bar'\nbaz 'bang'\nbip='bop')" => [error(:invalid_attribute_list, '"(foo=\'bar\' baz \'bang\'"'), 2], "%p{'foo' => 'bar' 'bar' => 'baz'}" => :compile, "%p{:foo => }" => :compile, "%p{=> 'bar'}" => :compile, "%p{'foo => 'bar'}" => :compile, "%p{:foo => 'bar}" => :compile, "%p{:foo => 'bar\"}" => :compile, # Regression tests "foo\n\n\n bar" => [error(:illegal_nesting_plain), 4], "%p/\n\n bar" => [error(:illegal_nesting_self_closing), 3], "%p foo\n\n bar" => [error(:illegal_nesting_line, 'p'), 3], "/ foo\n\n bar" => [error(:illegal_nesting_content), 3], "!!!\n\n bar" => [error(:illegal_nesting_header), 3], "- raise 'foo'\n\n\n\nbar" => ["foo", 1], "= 'foo'\n-raise 'foo'" => ["foo", 2], "\n\n\n- raise 'foo'" => ["foo", 4], "%p foo |\n bar |\n baz |\nbop\n- raise 'foo'" => ["foo", 5], "foo\n:ruby\n 1\n 2\n 3\n- raise 'foo'" => ["foo", 6], "foo\n:erb\n 1\n 2\n 3\n- raise 'foo'" => ["foo", 6], "foo\n:plain\n 1\n 2\n 3\n- raise 'foo'" => ["foo", 6], "foo\n:plain\n 1\n 2\n 3\n4\n- raise 'foo'" => ["foo", 7], "foo\n:plain\n 1\n 2\n 3\#{''}\n- raise 'foo'" => ["foo", 6], "foo\n:plain\n 1\n 2\n 3\#{''}\n4\n- raise 'foo'" => ["foo", 7], "foo\n:plain\n 1\n 2\n \#{raise 'foo'}" => ["foo", 5], "= raise 'foo'\nfoo\nbar\nbaz\nbang" => ["foo", 1], "- case 1\n\n- when 1\n - raise 'foo'" => ["foo", 4], }.freeze User = Struct.new('User', :id) CustomHamlClass = Struct.new(:id) do def haml_object_ref "my_thing" end end CpkRecord = Struct.new('CpkRecord', :id) do def to_key [*self.id] unless id.nil? end end def use_test_tracing(options) unless options[:filename] # use caller method name as fake filename. useful for debugging i = -1 caller[i+=1] =~ /`(.+?)'/ until $1 and $1.index('test_') == 0 options[:filename] = "(#{$1})" end options end def render(text, options = {}, &block) options = use_test_tracing(options) super end def engine(text, options = {}) options = use_test_tracing(options) Haml::Engine.new(text, options) end def setup @old_default_internal = Encoding.default_internal silence_warnings{Encoding.default_internal = nil} end def teardown silence_warnings{Encoding.default_internal = @old_default_internal} end def test_empty_render assert_equal "", render("") end def test_flexible_tabulation assert_equal("

    \nfoo\n

    \n\nbar\n\nbaz\n\n\n", render("%p\n foo\n%q\n bar\n %a\n baz")) assert_equal("

    \nfoo\n

    \n\nbar\n\nbaz\n\n\n", render("%p\n\tfoo\n%q\n\tbar\n\t%a\n\t\tbaz")) assert_equal("

    \n \t \t bar\n baz\n

    \n", render("%p\n :plain\n \t \t bar\n baz")) end def test_empty_render_should_remain_empty assert_equal('', render('')) end def test_attributes_should_render_correctly assert_equal("
    ", render(".atlantis{:style => 'ugly'}").chomp) end def test_css_id_as_attribute_should_be_appended_with_underscore assert_equal("
    ", render("#my_id{:id => '1'}").chomp) assert_equal("
    ", render("#my_id{:id => 1}").chomp) end def test_ruby_code_should_work_inside_attributes assert_equal("

    foo

    ", render("%p{:class => 1+2} foo").chomp) end def test_attributes_with_interpolation assert_equal("\n", render(<<-'HAML')) - base_url = "http://www.google.com" %iframe#test{src: "#{File.join base_url, '/abc/'}"} HAML end def test_class_attr_with_array assert_equal("

    foo

    \n", render("%p{:class => %w[a b]} foo")) # basic assert_equal("

    foo

    \n", render("%p.css{:class => %w[a b]} foo")) # merge with css assert_equal("

    foo

    \n", render("%p.css{:class => %w[css b]} foo")) # merge uniquely assert_equal("

    foo

    \n", render("%p{:class => [%w[a b], %w[c d]]} foo")) # flatten assert_equal("

    foo

    \n", render("%p{:class => [:a, :b] } foo")) # stringify assert_equal("

    foo

    \n", render("%p{:class => [nil, false] } foo")) # strip falsey assert_equal("

    foo

    \n", render("%p{:class => :a} foo")) # single stringify assert_equal("

    foo

    \n", render("%p{:class => false} foo")) # single falsey assert_equal("

    foo

    \n", render("%p(class='html'){:class => %w[a b]} foo")) # html attrs end def test_id_attr_with_array assert_equal("

    foo

    \n", render("%p{:id => %w[a b]} foo")) # basic assert_equal("

    foo

    \n", render("%p#css{:id => %w[a b]} foo")) # merge with css assert_equal("

    foo

    \n", render("%p{:id => [%w[a b], %w[c d]]} foo")) # flatten assert_equal("

    foo

    \n", render("%p{:id => [:a, :b] } foo")) # stringify assert_equal("

    foo

    \n", render("%p{:id => [nil, false] } foo")) # strip falsey assert_equal("

    foo

    \n", render("%p{:id => :a} foo")) # single stringify assert_equal("

    foo

    \n", render("%p{:id => false} foo")) # single falsey assert_equal("

    foo

    \n", render("%p(id='html'){:id => %w[a b]} foo")) # html attrs end def test_colon_in_class_attr assert_equal("

    \n", render("%p.foo:bar/")) end def test_colon_in_id_attr assert_equal("

    \n", render("%p#foo:bar/")) end def test_dynamic_attributes_with_no_content assert_equal(<

    HTML %p %a{:href => "http://" + "haml.info"} HAML end def test_attributes_with_to_s assert_equal(<

    HTML %p#foo{:id => 1+1} %p.foo{:class => 1+1} %p{:blaz => 1+1} %p{(1+1) => 1+1} HAML end def test_nil_should_render_empty_tag assert_equal("
    ", render(".no_attributes{:nil => nil}").chomp) end def test_strings_should_get_stripped_inside_tags assert_equal("
    This should have no spaces in front of it
    ", render(".stripped This should have no spaces in front of it").chomp) end def test_one_liner_should_be_one_line assert_equal("

    Hello

    ", render('%p Hello').chomp) end def test_one_liner_with_newline_shouldnt_be_one_line assert_equal("

    foo\nbar

    ", render('%p= "foo\nbar"').chomp) end def test_multi_render engine = engine("%strong Hi there!") assert_equal("Hi there!\n", engine.to_html) assert_equal("Hi there!\n", engine.to_html) assert_equal("Hi there!\n", engine.to_html) end def test_interpolation assert_equal("

    Hello World

    \n", render('%p Hello #{who}', locals: {who: 'World'}, escape_html: false)) assert_equal("

    \nHello World\n

    \n", render("%p\n Hello \#{who}", locals: {who: 'World'}, escape_html: false)) assert_equal("

    Hello World

    \n", render('%p Hello #{who}', locals: {who: 'World'}, escape_html: true)) assert_equal("

    \nHello World\n

    \n", render("%p\n Hello \#{who}", locals: {who: 'World'}, escape_html: true)) end def test_interpolation_with_instance_var scope = Object.new scope.instance_variable_set(:@who, 'World') assert_equal("

    Hello World

    \n", render('%p Hello #@who', scope: scope, escape_html: false)) assert_equal("

    \nHello World\n

    \n", render("%p\n Hello \#@who", scope: scope, escape_html: false)) assert_equal("

    Hello World

    \n", render('%p Hello #@who', scope: scope, escape_html: true)) assert_equal("

    \nHello World\n

    \n", render("%p\n Hello \#@who", scope: scope, escape_html: true)) end def test_interpolation_with_global $global_var_for_testing = 'World' assert_equal("

    Hello World

    \n", render('%p Hello #$global_var_for_testing', escape_html: false)) assert_equal("

    \nHello World\n

    \n", render("%p\n Hello \#$global_var_for_testing", escape_html: false)) assert_equal("

    Hello World

    \n", render('%p Hello #$global_var_for_testing', escape_html: true)) assert_equal("

    \nHello World\n

    \n", render("%p\n Hello \#$global_var_for_testing", escape_html: true)) ensure $global_var_for_testing = nil end def test_interpolation_in_the_middle_of_a_string assert_equal("\"title 'Title'. \"\n", render("\"title '\#{\"Title\"}'. \"")) end def test_interpolation_with_instance_var_in_the_middle_of_a_string scope = Object.new scope.instance_variable_set(:@title, 'Title') assert_equal("\"title 'Title'. \"\n", render("\"title '\#@title'. \"", :scope => scope)) end def test_interpolation_with_global_in_the_middle_of_a_string $global_var_for_testing = 'Title' assert_equal("\"title 'Title'. \"\n", render("\"title '\#$global_var_for_testing'. \"")) ensure $global_var_for_testing = nil end def test_interpolation_at_the_beginning_of_a_line assert_equal("

    2

    \n", render('%p #{1 + 1}')) assert_equal("

    \n2\n

    \n", render("%p\n \#{1 + 1}")) end def test_interpolation_with_instance_var_at_the_beginning_of_a_line scope = Object.new scope.instance_variable_set(:@foo, 2) assert_equal("

    2

    \n", render('%p #@foo', :scope => scope)) assert_equal("

    \n2\n

    \n", render("%p\n \#@foo", :scope => scope)) end def test_interpolation_with_global_at_the_beginning_of_a_line $global_var_for_testing = 2 assert_equal("

    2

    \n", render('%p #$global_var_for_testing')) assert_equal("

    \n2\n

    \n", render("%p\n \#$global_var_for_testing")) ensure $global_var_for_testing = nil end def test_escaped_interpolation assert_equal("

    Foo & Bar & Baz

    \n", render('%p& Foo #{"&"} Bar & Baz')) end def test_nil_tag_value_should_render_as_empty assert_equal("

    \n", render("%p= nil")) end def test_tag_with_failed_if_should_render_as_empty assert_equal("

    \n", render("%p= 'Hello' if false")) end def test_static_attributes_with_empty_attr assert_equal("\n", render("%img{:src => '/foo.png', :alt => ''}")) end def test_dynamic_attributes_with_empty_attr assert_equal("\n", render("%img{:width => nil, :src => '/foo.png', :alt => String.new}")) end def test_attribute_hash_with_newlines assert_equal("

    foop

    \n", render("%p{:a => 'b',\n :c => 'd'} foop")) assert_equal("

    \nfoop\n

    \n", render("%p{:a => 'b',\n :c => 'd'}\n foop")) assert_equal("

    \n", render("%p{:a => 'b',\n :c => 'd'}/")) assert_equal("

    \n", render("%p{:a => 'b',\n :c => 'd',\n :e => 'f'}")) end def test_attr_hashes_not_modified hash = {:color => 'red'} assert_equal(< {:hash => hash}))
    HTML %div{hash} .special{hash} %div{hash} HAML assert_equal(hash, {:color => 'red'}) end def test_semi_prerendered_tags assert_equal(<

    foo

    foo

    foo bar

    foo bar

    foo

    HTML %p{:a => 1 + 1} %p{:a => 1 + 1} foo %p{:a => 1 + 1}/ %p{:a => 1 + 1}= "foo" %p{:a => 1 + 1}= "foo\\nbar" %p{:a => 1 + 1}~ "foo\\nbar" %p{:a => 1 + 1} foo HAML end def test_end_of_file_multiline assert_equal("

    0

    \n

    1

    \n

    2

    \n", render("- for i in (0...3)\n %p= |\n i |")) end def test_cr_newline assert_equal("

    foo

    \n

    bar

    \n

    baz

    \n

    boom

    \n", render("%p foo\r%p bar\r\n%p baz\n\r%p boom")) end def test_textareas assert_equal("\n", render('%textarea= "Foo\n bar\n baz"')) assert_equal("
    Foo
      bar
       baz
    \n", render('%pre= "Foo\n bar\n baz"')) assert_equal("\n", render("%textarea #{'a' * 100}")) assert_equal("

    \n\n

    \n", render(<Foo bar baz
    HTML %pre %code :preserve Foo bar baz HAML end def test_boolean_attributes assert_equal("

    \n", render("%p{:foo => 'bar', :bar => true, :baz => 'true'}", :format => :html4)) assert_equal("

    \n", render("%p{:foo => 'bar', :bar => true, :baz => 'true'}", :format => :xhtml)) assert_equal("

    \n", render("%p{:foo => 'bar', :bar => false, :baz => 'false'}", :format => :html4)) assert_equal("

    \n", render("%p{:foo => 'bar', :bar => false, :baz => 'false'}", :format => :xhtml)) end def test_nuke_inner_whitespace_in_loops assert_equal(<foobarbaz HTML %ul< - for str in %w[foo bar baz] = str HAML end def test_both_whitespace_nukes_work_together assert_equal(<Foo Bar

    RESULT %p %q><= "Foo\\nBar" SOURCE end def test_nil_option assert_equal("

    \n", render('%p{:foo => "bar"}', :attr_wrapper => nil)) assert_equal("

    \n", render('%p{foo: "bar"}', :attr_wrapper => nil)) end def test_comment_with_crazy_nesting assert_equal(< foo bar HTML %html %body %img{:src => 'te'+'st'} = "foo\\nbar" HAML end def test_whitespace_nuke_with_both_newlines assert_equal("

    \nfoo\n

    \n", render('%p<= "\nfoo\n"')) assert_equal(<

    foo

    HTML %p %p<= "\\nfoo\\n" HAML end def test_whitespace_nuke_with_tags_and_else assert_equal(< foo HTML %a %b< - if false = "foo" - else foo HAML assert_equal(< foo HTML %a %b - if false = "foo" - else foo HAML end def test_outer_whitespace_nuke_with_empty_script assert_equal(< foo

    HTML %p foo = " " %a> HAML end def test_both_case_indentation_work_with_deeply_nested_code result = < other RESULT assert_equal(result, render(<One

    Three

    HTML - for name in ["One", "Two", "Three"] %p= name unless name == "Two" HAML end def test_end_with_method_call assert_equal("2|3|4b-a-r", render(< 2|3|4b-a-r

    HTML %p = [1, 2, 3].map do |i| - i + 1 - end.join("|") = "bar".gsub(/./) do |s| - s + "-" - end.gsub(/-$/) do |s| - '' HAML end def test_silent_end_with_stuff assert_equal(<hi!

    HTML - if true %p hi! - end if "foo".gsub(/f/) do - "z" - end + "bar" HAML end def test_multiline_with_colon_after_filter assert_equal(< "Bar", | :b => "Baz" }[:a] | HAML assert_equal(< "Bar", | :b => "Baz" }[:a] | HAML end def test_multiline_in_filter assert_equal(< false))
    bar
    HTML #foo{:class => ''} bar HAML end def test_escape_attrs_always assert_equal(< true))
    bar
    HTML #foo{:class => '"<>&"'} bar HAML end def test_escape_html html = < true)) &= "&" != "&" = "&" HAML assert_equal(html, render(< true)) &~ "&" !~ "&" ~ "&" HAML assert_equal(html, render(< true)) & \#{"&"} ! \#{"&"} \#{"&"} HAML assert_equal(html, render(< true)) &== \#{"&"} !== \#{"&"} == \#{"&"} HAML tag_html = <&

    &

    &

    HTML assert_equal(tag_html, render(< true)) %p&= "&" %p!= "&" %p= "&" HAML assert_equal(tag_html, render(< true)) %p&~ "&" %p!~ "&" %p~ "&" HAML assert_equal(tag_html, render(< true)) %p& \#{"&"} %p! \#{"&"} %p \#{"&"} HAML assert_equal(tag_html, render(< true)) %p&== \#{"&"} %p!== \#{"&"} %p== \#{"&"} HAML end def test_new_attrs_with_hash assert_equal("\n", render('%a(href="#")')) end def test_silent_script_with_hyphen_case assert_equal("", render("- a = 'foo-case-bar-case'")) end def test_silent_script_with_hyphen_end assert_equal("", render("- a = 'foo-end-bar-end'")) end def test_silent_script_with_hyphen_end_and_block silence_warnings do assert_equal(<foo-end

    bar-end

    HTML - ("foo-end-bar-end".gsub(/\\w+-end/) do |s| %p= s - end; nil) HAML end end def test_if_without_content_and_else assert_equal(<Foo\n", render('%a(href="#" rel="top") Foo')) assert_equal("Foo\n", render('%a(href="#") #{"Foo"}')) assert_equal("\n", render('%a(href="#\\"")')) end def test_case_assigned_to_var assert_equal(< true)) foo, HTML foo\#{"," if true} HAML end # HTML escaping tests def test_ampersand_equals_should_escape assert_equal("

    \nfoo & bar\n

    \n", render("%p\n &= 'foo & bar'", :escape_html => false)) end def test_ampersand_equals_inline_should_escape assert_equal("

    foo & bar

    \n", render("%p&= 'foo & bar'", :escape_html => false)) end def test_ampersand_equals_should_escape_before_preserve assert_equal("\n", render('%textarea&= "foo\nbar"', :escape_html => false)) end def test_bang_equals_should_not_escape assert_equal("

    \nfoo & bar\n

    \n", render("%p\n != 'foo & bar'", :escape_html => true)) end def test_bang_equals_inline_should_not_escape assert_equal("

    foo & bar

    \n", render("%p!= 'foo & bar'", :escape_html => true)) end def test_static_attributes_should_be_escaped assert_equal("\n", render("%img.atlantis{:style => 'ugly&stupid'}")) assert_equal("
    foo
    \n", render(".atlantis{:style => 'ugly&stupid'} foo")) assert_equal("

    foo

    \n", render("%p.atlantis{:style => 'ugly&stupid'}= 'foo'")) end def test_dynamic_attributes_should_be_escaped assert_equal("\n", render("%img{:width => nil, :src => '&foo.png', :alt => String.new}")) assert_equal("

    foo

    \n", render("%p{:width => nil, :src => '&foo.png', :alt => String.new} foo")) assert_equal("
    foo
    \n", render("%div{:width => nil, :src => '&foo.png', :alt => String.new}= 'foo'")) end def test_string_double_equals_should_be_esaped assert_equal("

    4&<

    \n", render("%p== \#{2+2}&\#{'<'}", :escape_html => true)) assert_equal("

    4&<

    \n", render("%p== \#{2+2}&\#{'<'}", :escape_html => false)) end def test_escaped_inline_string_double_equals assert_equal("

    4&<

    \n", render("%p&== \#{2+2}&\#{'<'}", :escape_html => true)) assert_equal("

    4&<

    \n", render("%p&== \#{2+2}&\#{'<'}", :escape_html => false)) end def test_unescaped_inline_string_double_equals assert_equal("

    4&<

    \n", render("%p!== \#{2+2}&\#{'<'}", :escape_html => true)) assert_equal("

    4&<

    \n", render("%p!== \#{2+2}&\#{'<'}", :escape_html => false)) end def test_escaped_string_double_equals assert_equal("

    \n4&<\n

    \n", render("%p\n &== \#{2+2}&\#{'<'}", :escape_html => true)) assert_equal("

    \n4&<\n

    \n", render("%p\n &== \#{2+2}&\#{'<'}", :escape_html => false)) end def test_unescaped_string_double_equals assert_equal("

    \n4&<\n

    \n", render("%p\n !== \#{2+2}&\#{'<'}", :escape_html => true)) assert_equal("

    \n4&<\n

    \n", render("%p\n !== \#{2+2}&\#{'<'}", :escape_html => false)) end def test_string_interpolation_should_be_esaped assert_equal("

    4&<

    \n", render("%p \#{2+2}&\#{'<'}", :escape_html => true)) assert_equal("

    4&<

    \n", render("%p \#{2+2}&\#{'<'}", :escape_html => false)) end def test_escaped_inline_string_interpolation assert_equal("

    4&<

    \n", render("%p& \#{2+2}&\#{'<'}", :escape_html => true)) assert_equal("

    4&<

    \n", render("%p& \#{2+2}&\#{'<'}", :escape_html => false)) end def test_unescaped_inline_string_interpolation assert_equal("

    4&<

    \n", render("%p! \#{2+2}&\#{'<'}", :escape_html => true)) assert_equal("

    4&<

    \n", render("%p! \#{2+2}&\#{'<'}", :escape_html => false)) end def test_escaped_string_interpolation assert_equal("

    \n4&<\n

    \n", render("%p\n & \#{2+2}&\#{'<'}", :escape_html => true)) assert_equal("

    \n4&<\n

    \n", render("%p\n & \#{2+2}&\#{'<'}", :escape_html => false)) end def test_escaped_string_interpolation_with_no_space assert_equal("<br>\n", render('&#{"
    "}')) assert_equal("<br>\n", render('%span&#{"
    "}')) end def test_unescaped_string_interpolation assert_equal("

    \n4&<\n

    \n", render("%p\n ! \#{2+2}&\#{'<'}", :escape_html => true)) assert_equal("

    \n4&<\n

    \n", render("%p\n ! \#{2+2}&\#{'<'}", :escape_html => false)) end def test_unescaped_string_interpolation_with_no_space assert_equal("
    \n", render('!#{"
    "}')) assert_equal("
    \n", render('%span!#{"
    "}')) end def test_scripts_should_respect_escape_html_option assert_equal("

    \nfoo & bar\n

    \n", render("%p\n = 'foo & bar'", :escape_html => true)) assert_equal("

    \nfoo & bar\n

    \n", render("%p\n = 'foo & bar'", :escape_html => false)) end def test_inline_scripts_should_respect_escape_html_option assert_equal("

    foo & bar

    \n", render("%p= 'foo & bar'", :escape_html => true)) assert_equal("

    foo & bar

    \n", render("%p= 'foo & bar'", :escape_html => false)) end def test_script_ending_in_comment_should_render_when_html_is_escaped assert_equal("foo&bar\n", render("= 'foo&bar' #comment", :escape_html => true)) end def test_script_with_if_shouldnt_output assert_equal(<foo

    HTML %p= "foo" %p= "bar" if false HAML end # Options tests def test_filename_and_line begin render("\n\n = abc", :filename => 'test', :line => 2) rescue Exception => e assert_kind_of Haml::SyntaxError, e assert_match(/test:4/, e.backtrace.first) end begin render("\n\n= 123\n\n= nil[]", :filename => 'test', :line => 2) rescue Exception => e assert_kind_of NoMethodError, e backtrace = e.backtrace backtrace.shift if rubinius? assert_match(/test:6/, backtrace.first) end end def test_stop_eval assert_equal("", render("= 'Hello'", :suppress_eval => true)) assert_equal("", render("- haml_concat 'foo'", :suppress_eval => true)) assert_equal("
    \n", render("#foo{:yes => 'no'}/", :suppress_eval => true)) assert_equal("
    \n", render("#foo{:yes => 'no', :call => a_function() }/", :suppress_eval => true)) assert_equal("
    \n", render("%div[1]/", :suppress_eval => true)) assert_equal("", render(":ruby\n Kernel.puts 'hello'", :suppress_eval => true)) end def test_doctypes assert_equal('', render('!!!', :format => :html5).strip) assert_equal('', render('!!! 5').strip) assert_equal('', render('!!! strict', :format => :xhtml).strip) assert_equal('', render('!!! frameset', :format => :xhtml).strip) assert_equal('', render('!!! mobile', :format => :xhtml).strip) assert_equal('', render('!!! basic', :format => :xhtml).strip) assert_equal('', render('!!! transitional', :format => :xhtml).strip) assert_equal('', render('!!!', :format => :xhtml).strip) assert_equal('', render('!!! strict', :format => :html4).strip) assert_equal('', render('!!! frameset', :format => :html4).strip) assert_equal('', render('!!! transitional', :format => :html4).strip) assert_equal('', render('!!!', :format => :html4).strip) end def test_attr_wrapper assert_equal("

    \n", render("%p{ :strange => 'attrs'}", :attr_wrapper => '*')) assert_equal("

    \n", render("%p{ :escaped => 'quo\"te'}", :attr_wrapper => '"')) assert_equal("

    \n", render("%p{ :escaped => 'quo\\'te'}", :attr_wrapper => '"')) assert_equal("

    \n", render("%p{ :escaped => 'q\\'uo\"te'}", :attr_wrapper => '"')) assert_equal("\n", render("!!! XML", :attr_wrapper => '"', :format => :xhtml)) end def test_autoclose_option assert_equal("\n", render("%flaz{:foo => 'bar'}", :autoclose => ["flaz"])) assert_equal(< [/^flaz/])) HTML %flaz %flaznicate %flan HAML end def test_attrs_parsed_correctly assert_equal("

    \n", render("%p{'foo,bar' => 'baz, qux'}")) assert_equal("

    \n", render("%p{ :escaped => \"quo\#{2 + 2}te\"}")) end def test_correct_parsing_with_brackets assert_equal("

    {tada} foo

    \n", render("%p{:class => 'foo'} {tada} foo")) assert_equal("

    deep {nested { things }}

    \n", render("%p{:class => 'foo'} deep {nested { things }}")) assert_equal("

    {a { d

    \n", render("%p{{:class => 'foo'}, :class => 'bar'} {a { d")) assert_equal("

    a}

    \n", render("%p{:foo => 'bar'} a}")) foo = [] foo[0] = Struct.new('Foo', :id).new assert_equal("

    New User]

    \n", render("%p[foo[0]] New User]", :locals => {:foo => foo})) assert_equal("

    New User]

    \n", render("%p[foo[0], :prefix] New User]", :locals => {:foo => foo})) foo[0].id = 1 assert_equal("

    New User]

    \n", render("%p[foo[0]] New User]", :locals => {:foo => foo})) assert_equal("

    New User]

    \n", render("%p[foo[0], :prefix] New User]", :locals => {:foo => foo})) end def test_empty_attrs assert_equal("

    empty

    \n", render("%p{ :attr => '' } empty")) assert_equal("

    empty

    \n", render("%p{ :attr => x } empty", :locals => {:x => ''})) end def test_nil_attrs assert_equal("

    nil

    \n", render("%p{ :attr => nil } nil")) assert_equal("

    nil

    \n", render("%p{ :attr => x } nil", :locals => {:x => nil})) end def test_nil_id_with_syntactic_id assert_equal("

    nil

    \n", render("%p#foo{:id => nil} nil")) assert_equal("

    nil

    \n", render("%p#foo{{:id => 'bar'}, :id => nil} nil")) assert_equal("

    nil

    \n", render("%p#foo{{:id => nil}, :id => 'bar'} nil")) end def test_nil_class_with_syntactic_class assert_equal("

    nil

    \n", render("%p.foo{:class => nil} nil")) assert_equal("

    nil

    \n", render("%p.bar.foo{:class => nil} nil")) assert_equal("

    nil

    \n", render("%p.foo{{:class => 'bar'}, :class => nil} nil")) assert_equal("

    nil

    \n", render("%p.foo{{:class => nil}, :class => 'bar'} nil")) end def test_locals assert_equal("

    Paragraph!

    \n", render("%p= text", :locals => { :text => "Paragraph!" })) end def test_dynamic_attrs_shouldnt_register_as_literal_values assert_equal("

    \n", render('%p{:a => "b#{1 + 1}c"}')) assert_equal("

    \n", render("%p{:a => 'b' + (1 + 1).to_s + 'c'}")) end def test_dynamic_attrs_with_self_closed_tag assert_equal("\nc\n", render("%a{'b' => 1 + 1}/\n= 'c'\n")) end EXCEPTION_MAP.each do |key, value| define_method("test_exception (#{key.inspect})") do begin silence_warnings do render(key, :filename => "(test_exception (#{key.inspect}))") end rescue Exception => err value = [value] unless value.is_a?(Array) expected_message, line_no = value line_no ||= key.split("\n").length if expected_message == :compile assert_match(/(compile error|syntax error|unterminated string|expecting)/, err.message, "Line: #{key}") else assert_equal(expected_message, err.message, "Line: #{key}") end else assert(false, "Exception not raised for\n#{key}") end end end def test_exception_line render("a\nb\n!!!\n c\nd") rescue Haml::SyntaxError => e assert_equal("(test_exception_line):4", e.backtrace[0]) else assert(false, '"a\nb\n!!!\n c\nd" doesn\'t produce an exception') end def test_exception render("%p\n hi\n %a= undefined\n= 12") rescue Exception => e backtrace = e.backtrace backtrace.shift if rubinius? assert_match("(test_exception):3", backtrace[0]) else # Test failed... should have raised an exception assert(false) end def test_compile_error render("a\nb\n- fee)\nc") rescue Exception => e assert_match(/\(test_compile_error\):3:/i, e.message) assert_match(/(syntax error|expecting \$end)/i, e.message) else assert(false, '"a\nb\n- fee)\nc" doesn\'t produce an exception!') end def test_unbalanced_brackets render('foo #{1 + 5} foo #{6 + 7 bar #{8 + 9}') rescue Haml::SyntaxError => e assert_equal(Haml::Error.message(:unbalanced_brackets), e.message) end def test_single_line_comments_are_interpolated assert_equal("\n", render('/ Hello #{1 + 1}')) end def test_single_line_comments_are_not_interpolated_with_suppress_eval assert_equal("\n", render('/ Hello #{1 + 1}', :suppress_eval => true)) end def test_single_line_comments_with_interpolation_dont_break_tabulation assert_equal("\nconcatted\n", render("/ Hello \#{1 + 1}\n- haml_concat 'concatted'")) end def test_balanced_conditional_comments assert_equal("\n", render("/[if !(IE 6)|(IE 7)] Bracket: ]")) end def test_downlevel_revealed_conditional_comments assert_equal(" A comment \n", render("/![if !IE] A comment")) end def test_downlevel_revealed_conditional_comments_block assert_equal("\nA comment\n\n", render("/![if !IE]\n A comment")) end def test_local_assigns_dont_modify_class assert_equal("bar\n", render("= foo", :locals => {:foo => 'bar'})) assert_nil(defined?(foo)) end def test_object_ref_with_nil_id user = User.new assert_equal("

    New User

    \n", render("%p[user] New User", :locals => {:user => user})) end def test_object_ref_before_attrs user = User.new 42 assert_equal("

    New User

    \n", render("%p[user]{:style => 'width: 100px;'} New User", :locals => {:user => user})) end def test_object_ref_with_custom_haml_class custom = CustomHamlClass.new 42 assert_equal("

    My Thing

    \n", render("%p[custom]{:style => 'width: 100px;'} My Thing", :locals => {:custom => custom})) end def test_object_ref_with_multiple_ids cpk_record = CpkRecord.new([42,6,9]) assert_equal("

    CPK Record

    \n", render("%p[cpk_record]{:style => 'width: 100px;'} CPK Record", :locals => {:cpk_record => cpk_record})) end def test_non_literal_attributes assert_equal("

    \n", render("%p{a2, a1, :a3 => 'baz'}", :locals => {:a1 => {:a1 => 'foo'}, :a2 => {:a2 => 'bar'}})) end def test_render_should_accept_a_binding_as_scope string = "This is a string!".dup string.instance_variable_set(:@var, "Instance variable") b = string.instance_eval do var = "Local variable" # Silence unavoidable warning; Ruby doesn't know we're going to use this # later. nil if var binding end assert_equal("

    THIS IS A STRING!

    \n

    Instance variable

    \n

    Local variable

    \n", render("%p= upcase\n%p= @var\n%p= var", :scope => b)) end def test_yield_should_work_with_binding assert_equal("12\nFOO\n", render("= yield\n= upcase", :scope => "foo".dup.instance_eval{binding}) { 12 }) end def test_yield_should_work_with_def_method s = "foo".dup engine("= yield\n= upcase").def_method(s, :render) assert_equal("12\nFOO\n", s.render { 12 }) end def test_def_method_with_module engine("= yield\n= upcase").def_method(String, :render_haml) assert_equal("12\nFOO\n", "foo".dup.render_haml { 12 }) end def test_def_method_locals obj = Object.new engine("%p= foo\n.bar{:baz => baz}= boom").def_method(obj, :render, :foo, :baz, :boom) assert_equal("

    1

    \n
    3
    \n", obj.render(:foo => 1, :baz => 2, :boom => 3)) end def test_render_proc_locals proc = engine("%p= foo\n.bar{:baz => baz}= boom").render_proc(Object.new, :foo, :baz, :boom) assert_equal("

    1

    \n
    3
    \n", proc[:foo => 1, :baz => 2, :boom => 3]) end def test_render_proc_with_binding assert_equal("FOO\n", engine("= upcase").render_proc("foo".dup.instance_eval{binding}).call) end def test_haml_buffer_gets_reset_even_with_exception scope = Object.new render("- raise Haml::Error", :scope => scope) assert(false, "Expected exception") rescue Exception assert_nil(scope.send(:haml_buffer)) end def test_def_method_haml_buffer_gets_reset_even_with_exception scope = Object.new engine("- raise Haml::Error").def_method(scope, :render) scope.render assert(false, "Expected exception") rescue Exception assert_nil(scope.send(:haml_buffer)) end def test_render_proc_haml_buffer_gets_reset_even_with_exception scope = Object.new proc = engine("- raise Haml::Error").render_proc(scope) proc.call assert(false, "Expected exception") rescue Exception assert_nil(scope.send(:haml_buffer)) end def test_render_proc_should_raise_haml_syntax_error_not_ruby_syntax_error assert_raises(Haml::SyntaxError) do Haml::Engine.new("%p{:foo => !}").render_proc(Object.new, :foo).call end end def test_render_should_raise_haml_syntax_error_not_ruby_syntax_error assert_raises(Haml::SyntaxError) do Haml::Engine.new("%p{:foo => !}").render end end def test_spacing_inside_tag assert_equal("
    \n
    \n

    hello world

    \n
    \n
    \n", render("#outer\n #inner\n %p hello world")) assert_equal("

    #{'s' * 75}

    \n", render("%p #{'s' * 75}")) assert_equal("

    #{'s' * 75}

    \n", render("%p= 's' * 75")) end def test_remove_whitespace_true assert_equal("

    hello world

    ", render("#outer\n #inner\n %p hello world", :remove_whitespace => true)) assert_equal("

    hello world

    foo   bar\nbaz

    ", render(< true)) %p hello world %pre foo bar baz HAML assert_equal("
    foo bar
    ", render('%div foo bar', :remove_whitespace => true)) end def test_auto_preserve assert_equal("
    foo
    bar
    \n", render('%pre="foo\nbar"')) assert_equal("
    foo\nbar
    \n", render("%pre\n foo\n bar")) end def test_xhtml_output_option assert_equal "

    \n
    \n

    \n", render("%p\n %br", :format => :xhtml) assert_equal "
    \n", render("%a/", :format => :xhtml) end def test_arbitrary_output_option assert_raises_message(Haml::Error, "Invalid output format :html1") do engine("%br", :format => :html1) end end def test_static_hashes assert_equal("\n", render("%a{:b => 'a => b'}", :suppress_eval => true)) assert_equal("\n", render("%a{:b => 'a, b'}", :suppress_eval => true)) assert_equal("\n", render('%a{:b => "a\tb"}', :suppress_eval => true)) assert_equal("\n", render('%a{:b => "a\\#{foo}b"}', :suppress_eval => true)) assert_equal("\n", render("%a{:b => '#f00'}", :suppress_eval => true)) end def test_dynamic_hashes_with_suppress_eval assert_equal("\n", render('%a{:b => "a #{1 + 1} b", :c => "d"}', :suppress_eval => true)) end def test_interpolates_instance_vars_in_attribute_values scope = Object.new scope.instance_variable_set :@foo, 'bar' assert_equal("\n", render('%a{:b => "a #@foo b"}', :scope => scope)) end def test_interpolates_global_vars_in_attribute_values # make sure the value isn't just interpolated in during template compilation engine = Haml::Engine.new('%a{:b => "a #$global_var_for_testing b"}') $global_var_for_testing = 'bar' assert_equal("\n", engine.to_html) ensure $global_var_for_testing = nil end def test_utf8_attrs assert_equal("\n", render("%a{:href => 'héllo'}")) assert_equal("\n", render("%a(href='héllo')")) end # HTML 4.0 def test_html_has_no_self_closing_tags assert_equal "

    \n
    \n

    \n", render("%p\n %br", :format => :html4) assert_equal "
    \n", render("%br/", :format => :html4) end def test_html_renders_empty_node_with_closing_tag assert_equal "
    \n", render(".foo", :format => :html4) end def test_html_doesnt_add_slash_to_self_closing_tags assert_equal "\n", render("%a/", :format => :html4) assert_equal "\n", render("%a{:foo => 1 + 1}/", :format => :html4) assert_equal "\n", render("%meta", :format => :html4) assert_equal "\n", render("%meta{:foo => 1 + 1}", :format => :html4) end def test_html_ignores_xml_prolog_declaration assert_equal "", render('!!! XML', :format => :html4) end def test_html_has_different_doctype assert_equal %{\n}, render('!!!', :format => :html4) end # because anything before the doctype triggers quirks mode in IE def test_xml_prolog_and_doctype_dont_result_in_a_leading_whitespace_in_html refute_match(/^\s+/, render("!!! xml\n!!!", :format => :html4)) end # HTML5 def test_html5_doctype assert_equal %{\n}, render('!!!', :format => :html5) end # HTML5 custom data attributes def test_html5_data_attributes_without_hyphenation assert_equal("
    \n", render("%div{:data => {:author_id => 123, :foo => 'bar', :biz => 'baz'}}", :hyphenate_data_attrs => false)) assert_equal("
    \n", render("%div{:data => {:one_plus_one => 1+1}}", :hyphenate_data_attrs => false)) assert_equal("
    \n", render(%{%div{:data => {:foo => %{Here's a "quoteful" string.}}}}, :hyphenate_data_attrs => false)) #' end def test_html5_data_attributes_with_hyphens assert_equal("
    \n", render("%div{:data => {:foo_bar => 'blip'}}")) assert_equal("
    \n", render("%div{:data => {:foo_bar => 'blip', :baz => 'bang'}}")) end def test_html5_arbitrary_hash_valued_attributes_with assert_equal("
    \n", render("%div{:aria => {:foo => 'blip'}}")) assert_equal("
    \n", render("%div{:foo => {:baz => 'bang'}}")) end def test_arbitrary_attribute_hash_merging assert_equal(%Q{
    \n}, render(<<-HAML)) - h1 = {:aria => {:foo => :bar}} - h2 = {:baz => :qux} %a{h1, :aria => h2} HAML end def test_hash_method_call_in_attributes assert_equal(%Q{\n}, render(<<-HAML)) - hash = {:hoge => :fuga} %a{{foo: 'bar'}.merge(hash)} HAML end def test_html5_data_attributes_with_nested_hash assert_equal("
    \n", render(<<-HAML)) - hash = {:a => {:b => 'c'}} - hash[:d] = hash %div{:data => hash} HAML end def test_html5_data_attributes_with_nested_hash_and_without_hyphenation assert_equal("
    \n", render(<<-HAML, :hyphenate_data_attrs => false)) - hash = {:a => {:b => 'c'}} - hash[:d] = hash %div{:data => hash} HAML end def test_html5_data_attributes_with_multiple_defs # Should always use the more-explicit attribute assert_equal("
    \n", render("%div{:data => {:foo => 'first'}, 'data-foo' => 'second'}")) assert_equal("
    \n", render("%div{'data-foo' => 'first', :data => {:foo => 'second'}}")) end def test_html5_data_attributes_with_attr_method obj = Object.new def obj.data_hash {:data => {:foo => "bar", :baz => "bang"}} end def obj.data_val {:data => "dat"} end assert_equal("
    \n", render("%div{data_hash, :data => {:foo => 'blip', :brat => 'wurst'}}", scope: obj)) assert_equal("
    \n", render("%div{data_hash, 'data-foo' => 'blip'}", scope: obj)) assert_equal("
    \n", render("%div{data_hash, :data => 'dat'}", scope: obj)) assert_equal("
    \n", render("%div{data_val, :data => {:foo => 'blip', :brat => 'wurst'}}", scope: obj)) end def test_html5_data_attributes_with_identical_attribute_values assert_equal("
    \n", render("%div{:data => {:x => 50, :y => 50}}")) end def test_xml_doc_using_html5_format_and_mime_type assert_equal(< :html5, :mime_type => 'text/xml' }))
    XML !!! XML %root %element/ %hr HAML end def test_xml_doc_using_html4_format_and_mime_type assert_equal(< :html4, :mime_type => 'text/xml' }))
    XML !!! XML %root %element/ %hr HAML end # New attributes def test_basic_new_attributes assert_equal("bar\n", render("%a() bar")) assert_equal("bar\n", render("%a(href='foo') bar")) assert_equal("baz\n", render(%q{%a(b="c" c='d' d="e") baz})) end def test_new_attribute_ids assert_equal("
    \n", render("#foo(id='bar')")) assert_equal("
    \n", render("#foo{:id => 'bar'}(id='baz')")) assert_equal("
    \n", render("#foo(id='baz'){:id => 'bar'}")) foo = User.new(42) assert_equal("
    \n", render("#foo(id='baz'){:id => 'bar'}[foo]", :locals => {:foo => foo})) assert_equal("
    \n", render("#foo(id='baz')[foo]{:id => 'bar'}", :locals => {:foo => foo})) assert_equal("
    \n", render("#foo[foo](id='baz'){:id => 'bar'}", :locals => {:foo => foo})) assert_equal("
    \n", render("#foo[foo]{:id => 'bar'}(id='baz')", :locals => {:foo => foo})) end def test_new_attribute_classes assert_equal("
    \n", render(".foo(class='bar')")) assert_equal("
    \n", render(".foo{:class => 'bar'}(class='baz')")) assert_equal("
    \n", render(".foo(class='baz'){:class => 'bar'}")) foo = User.new(42) assert_equal("
    \n", render(".foo(class='baz'){:class => 'bar'}[foo]", :locals => {:foo => foo})) assert_equal("
    \n", render(".foo[foo](class='baz'){:class => 'bar'}", :locals => {:foo => foo})) assert_equal("
    \n", render(".foo[foo]{:class => 'bar'}(class='baz')", :locals => {:foo => foo})) end def test_dynamic_new_attributes assert_equal("bar\n", render("%a(href=foo) bar", :locals => {:foo => 12})) assert_equal("bar\n", render("%a(b=b c='13' d=d) bar", :locals => {:b => 12, :d => 14})) end def test_new_attribute_interpolation assert_equal("bar\n", render('%a(href="1#{1 + 1}") bar')) assert_equal("bar\n", render(%q{%a(href='2: #{1 + 1}, 3: #{foo}') bar}, :locals => {:foo => 3})) assert_equal(%Q{bar\n}, render('%a(href="1\#{1 + 1}") bar')) end def test_truthy_new_attributes assert_equal("bar\n", render("%a(href) bar", :format => :xhtml)) assert_equal("bar\n", render("%a(href bar='baz') bar", :format => :html5)) assert_equal("bar\n", render("%a(href=true) bar")) assert_equal("bar\n", render("%a(href=false) bar")) end def test_new_attribute_parsing assert_equal("bar\n", render("%a(a2=b2) bar", :locals => {:b2 => 'b2'})) assert_equal(%Q{bar\n}, render(%q{%a(a="#{'foo"bar'}") bar})) #' assert_equal(%Q{bar\n}, render(%q{%a(a="#{"foo'bar"}") bar})) #' assert_equal(%Q{bar\n}, render(%q{%a(a='foo"bar') bar})) assert_equal(%Q{bar\n}, render(%q{%a(a="foo'bar") bar})) assert_equal("bar\n", render("%a(a:b='foo') bar")) assert_equal("bar\n", render("%a(a = 'foo' b = 'bar') bar")) assert_equal("bar\n", render("%a(a = foo b = bar) bar", :locals => {:foo => 'foo', :bar => 'bar'})) assert_equal("(b='bar')\n", render("%a(a='foo')(b='bar')")) assert_equal("baz\n", render("%a(a='foo)bar') baz")) assert_equal("baz\n", render("%a( a = 'foo' ) baz")) end def test_new_attribute_escaping assert_equal(%Q{bar\n}, render(%q{%a(a="foo \" bar") bar})) assert_equal(%Q{bar\n}, render(%q{%a(a="foo \\\\\" bar") bar})) assert_equal(%Q{bar\n}, render(%q{%a(a='foo \' bar') bar})) assert_equal(%Q{bar\n}, render(%q{%a(a='foo \\\\\' bar') bar})) assert_equal(%Q{bar\n}, render(%q{%a(a="foo \\\\ bar") bar})) assert_equal(%Q{bar\n}, render(%q{%a(a="foo \#{1 + 1} bar") bar})) end def test_multiline_new_attribute assert_equal("bar\n", render("%a(a='b'\n c='d') bar")) assert_equal("bar\n", render("%a(a='b' b='c'\n c='d' d=e\n e='f' f='j') bar", :locals => {:e => 'e'})) end def test_new_and_old_attributes assert_equal("bar\n", render("%a(a='b'){:c => 'd'} bar")) assert_equal("bar\n", render("%a{:c => 'd'}(a='b') bar")) assert_equal("bar\n", render("%a(c='d'){:a => 'b'} bar")) assert_equal("bar\n", render("%a{:a => 'b'}(c='d') bar")) # Old-style always takes precedence over new-style, # because theoretically old-style could have arbitrary end-of-method-call syntax. assert_equal("bar\n", render("%a{:a => 'b'}(a='d') bar")) assert_equal("bar\n", render("%a(a='d'){:a => 'b'} bar")) assert_equal("bar\n", render("%a{:a => 'b',\n:b => 'c'}(c='d'\nd='e') bar")) locals = {:b => 'b', :d => 'd'} assert_equal("

    \n", render("%p{:a => b}(c=d)", :locals => locals)) assert_equal("

    \n", render("%p(a=b){:c => d}", :locals => locals)) assert_equal("

    \n

    \n", render("%p(id=b){id:d}\n%p(id=b){id:d}", locals: locals)) end def test_attributes_sort_order # "," < "-" < "0" < "=" < "a" assert_equal(<<-HTML, render(<<-HAML))
    HTML - a = 4 %div{ a: a, 'a-' => 2, aa: 5, a0: 3, 'a,' => 1 } - hash = { a: a, 'a-' => 2, aa: 5, a0: 3, 'a,' => 1 } %div{ hash } HAML # (no char) < "," < "-" < "0" < "a" assert_equal(<<-HTML, render(<<-HAML))
    HTML - a = true %div{ a: a, 'a-' => 2, aa: 4, a0: 3, 'a,' => 1 } - hash = { a: a, 'a-' => 2, aa: 4, a0: 3, 'a,' => 1 } %div{ hash } HAML # "," < "-" < "0" (with hyphenation) assert_equal(<<-HTML, render(<<-HAML))
    HTML - a = { a: 2 } %div{ a: a, a0: 3, 'a,' => 1 } - hash = { a: a, a0: 3, 'a,' => 1 } %div{ hash } HAML # "A" < "_" < "a" (with underscoration) assert_equal(<<-HTML, render(<<-HAML, hyphenate_data_attrs: false))
    HTML - a = { a: { a: 2 } } %div{ a: a, 'a-aa' => 3, 'a-aA' => 1 } - hash = { a: a, 'a-aa' => 3, 'a-aA' => 1 } %div{ hash } HAML end # Ruby Multiline def test_silent_ruby_multiline assert_equal(<foo

    HTML - foo = ["bar", "baz", "bang"] = foo.join(", ") %p foo HAML end def test_loud_ruby_multiline assert_equal(<foo

    bar

    HTML = ["bar", "baz", "bang"].join(", ") %p foo %p bar HAML end def test_ruby_multiline_with_punctuated_methods_is_continuation assert_equal(<foo

    bar

    HTML = ["bar", " ".strip!, "".empty?, "bang"].join(", ") %p foo %p bar HAML end def test_ruby_character_literals_are_not_continuation html = ",\n,\n

    foo

    \n" assert_equal(html, render(<foo

    bar

    HTML &= ["bar<", "baz", "bang"].join(", ") %p foo %p bar HAML end def test_unescaped_loud_ruby_multiline assert_equal(< true)) bar<, baz, bang

    foo

    bar

    HTML != ["bar<", "baz", "bang"].join(", ") %p foo %p bar HAML end def test_flattened_loud_ruby_multiline assert_equal(<bar baz bang

    foo

    bar

    HTML ~ "
    " + ["bar",
                 "baz",
                 "bang"].join("\\n") + "
    " %p foo %p bar HAML end def test_loud_ruby_multiline_with_block assert_equal(<foo

    bar

    HTML = ["bar", "baz", "bang"].map do |str| - str.gsub("ba", "fa") %p foo %p bar HAML end def test_silent_ruby_multiline_with_block assert_equal(<foo

    bar

    HTML - ["bar", "baz", "bang"].map do |str| = str.gsub("ba", "fa") %p foo %p bar HAML end def test_ruby_multiline_in_tag assert_equal(<foo, bar, baz

    foo

    bar

    HTML %p= ["foo", "bar", "baz"].join(", ") %p foo %p bar HAML end def test_escaped_ruby_multiline_in_tag assert_equal(<foo<, bar, baz

    foo

    bar

    HTML %p&= ["foo<", "bar", "baz"].join(", ") %p foo %p bar HAML end def test_unescaped_ruby_multiline_in_tag assert_equal(< true))

    foo<, bar, baz

    foo

    bar

    HTML %p!= ["foo<", "bar", "baz"].join(", ") %p foo %p bar HAML end def test_ruby_multiline_with_normal_multiline assert_equal(<foo

    bar

    HTML = "foo" + | "bar" + | ["bar", | "baz", "bang"].join(", ") %p foo %p bar HAML end def test_ruby_multiline_after_filter assert_equal(<foo

    bar

    HTML :plain foo bar = ["bar", "baz", "bang"].join(", ") %p foo %p bar HAML end # Encodings def test_utf_8_bom assert_equal <

    baz

    HTML \xEF\xBB\xBF.foo %p baz HAML end def test_default_encoding assert_equal(Encoding.find("utf-8"), render(< "ascii-8bit"))

    bâr

    föö

    HTML %p bâr %p föö HAML end def test_convert_template_render_proc assert_converts_template_properly {|e| e.render_proc.call} end def test_convert_template_render assert_converts_template_properly {|e| e.render} end def test_convert_template_def_method assert_converts_template_properly do |e| o = Object.new e.def_method(o, :render) o.render end end def test_encoding_error render("foo\nbar\nb\xFEaz".dup.force_encoding("utf-8")) assert(false, "Expected exception") rescue Haml::Error => e assert_equal(3, e.line) assert_match(/Invalid .* character/, e.message) end def test_ascii_incompatible_encoding_error template = "foo\nbar\nb_z".encode("utf-16le") template[9] = "\xFE".dup.force_encoding("utf-16le") render(template) assert(false, "Expected exception") rescue Haml::Error => e assert_equal(3, e.line) assert_match(/Invalid .* character/, e.message) end def test_same_coding_comment_as_encoding assert_renders_encoded(<bâr

    föö

    HTML -# coding: utf-8 %p bâr %p föö HAML end def test_coding_comments assert_valid_encoding_comment("-# coding: ibm866") assert_valid_encoding_comment("-# CodINg: IbM866") assert_valid_encoding_comment("-#coding:ibm866") assert_valid_encoding_comment("-# CodINg= ibm866") assert_valid_encoding_comment("-# foo BAR FAOJcoding: ibm866") assert_valid_encoding_comment("-# coding: ibm866 ASFJ (&(&#!$") assert_valid_encoding_comment("-# -*- coding: ibm866") assert_valid_encoding_comment("-# coding: ibm866 -*- coding: blah") assert_valid_encoding_comment("-# -*- coding: ibm866 -*-") assert_valid_encoding_comment("-# -*- encoding: ibm866 -*-") assert_valid_encoding_comment('-# -*- coding: "ibm866" -*-') assert_valid_encoding_comment("-#-*-coding:ibm866-*-") assert_valid_encoding_comment("-#-*-coding:ibm866-*-") assert_valid_encoding_comment("-# -*- foo: bar; coding: ibm866; baz: bang -*-") assert_valid_encoding_comment("-# foo bar coding: baz -*- coding: ibm866 -*-") assert_valid_encoding_comment("-# -*- coding: ibm866 -*- foo bar coding: baz") end def test_different_coding_than_system assert_renders_encoded(<тАЬ

    HTML %p тАЬ HAML end def test_block_spacing assert render(<<-HAML) - foo = ["bar", "baz", "kni"] - foo.each do | item | = item HAML rescue ::SyntaxError flunk("Should not have raised syntax error") end def test_tracing result = render('%p{:class => "hello"}', :trace => true, :filename => 'foo').strip assert_equal "

    ", result end def test_unsafe_dynamic_attribute_name_raises_invalid_attribute_name_error assert_raises(Haml::InvalidAttributeNameError) do render(<<-HAML) - params = { 'x />
    'hello' } %div{ data: params } HAML end end def test_unsafe_static_attribute_name_raises_invalid_attribute_name_error assert_raises(Haml::InvalidAttributeNameError) do render(<<-HAML) %div{ 'x />
    'hello' } HAML end end def test_engine_reflects_defaults defaults = Haml::Options.defaults.dup Haml::Options.defaults[:attr_wrapper] = '"' assert_equal %Q[\n], Haml::Engine.new('%a(a="a")').render ensure Haml::Options.defaults.replace(defaults) end private def assert_valid_encoding_comment(comment) assert_renders_encoded(<ЖЛЫ

    тАЬ

    HTML #{comment} %p ЖЛЫ %p тАЬ HAML end def assert_converts_template_properly engine = Haml::Engine.new(< "macRoman") %p bâr %p föö HAML assert_encoded_equal(<bâr

    föö

    HTML end def assert_renders_encoded(html, haml) result = render(haml) assert_encoded_equal html, result end def assert_encoded_equal(expected, actual) assert_equal expected.encoding, actual.encoding assert_equal expected, actual end end haml-5.1.2/test/erb/000077500000000000000000000000001352226600500141705ustar00rootroot00000000000000haml-5.1.2/test/erb/_av_partial_1.erb000066400000000000000000000004431352226600500173640ustar00rootroot00000000000000

    This is a pretty complicated partial

    It has several nested partials,

      <% 5.times do %>
    • Partial: <% @nesting = 5 %> <%= render :partial => 'erb/av_partial_2' %> <% end %>
    haml-5.1.2/test/erb/_av_partial_2.erb000066400000000000000000000003651352226600500173700ustar00rootroot00000000000000<% @nesting -= 1 %>

    This is a crazy deep-nested partial.

    Nesting level <%= @nesting %>

    <% if @nesting > 0 %> <%= render :partial => 'erb/av_partial_2' %> <% end %>
    haml-5.1.2/test/erb/action_view.erb000066400000000000000000000042331352226600500171730ustar00rootroot00000000000000 Hampton Catlin Is Totally Awesome

    This is very much like the standard template, except that it has some ActionView-specific stuff. It's only used for benchmarking.

    <%= render :partial => 'erb/av_partial_1' %>
    Yes, ladies and gentileman. He is just that egotistical. Fantastic! This should be multi-line output The question is if this would translate! Ahah! <%= 1 + 9 + 8 + 2 %> <%# numbers should work and this should be ignored %>
    <% 120.times do |number| -%> <%= number %> <% end -%>
    <%= " Quotes should be loved! Just like people!" %>
    Wow.

    <%= "Holy cow " + "multiline " + "tags! " + "A pipe (|) even!" %> <%= [1, 2, 3].collect { |n| "PipesIgnored|" } %> <%= [1, 2, 3].collect { |n| n.to_s }.join("|") %>

    <% foo = String.new foo << "this" foo << " shouldn't" foo << " evaluate" %> <%= foo + "but now it should!" %> <%# Woah crap a comment! %>
      <% ('a'..'f').each do |a|%>
    • <%= a %> <% end %>
      <%= @should_eval = "with this text" %>
      <%= [ 104, 101, 108, 108, 111 ].map do |byte| byte.chr end %> haml-5.1.2/test/erb/standard.erb000066400000000000000000000037171352226600500164720ustar00rootroot00000000000000 Hampton Catlin Is Totally Awesome
      Yes, ladies and gentileman. He is just that egotistical. Fantastic! This should be multi-line output The question is if this would translate! Ahah! <%= 1 + 9 + 8 + 2 %> <%# numbers should work and this should be ignored %>
      <% 120.times do |number| -%> <%= number %> <% end -%>
      <%= " Quotes should be loved! Just like people!" %>
      Wow.

      <%= "Holy cow " + "multiline " + "tags! " + "A pipe (|) even!" %> <%= [1, 2, 3].collect { |n| "PipesIgnored|" }.join %> <%= [1, 2, 3].collect { |n| n.to_s }.join("|") %>

      <% bar = 17 %>
      <% foo = String.new foo << "this" foo << " shouldn't" foo << " evaluate" %> <%= foo + "but now it should!" %> <%# Woah crap a comment! %>
        <% ('a'..'f').each do |a|%>
      • <%= a %>
      • <% end %>
        <%= @should_eval = "with this text" %>
        <%= "foo".each_line do |line| nil end %> haml-5.1.2/test/filters_test.rb000066400000000000000000000204741352226600500164630ustar00rootroot00000000000000# frozen_string_literal: true require 'test_helper' class FiltersTest < Haml::TestCase test "should be registered as filters when including Haml::Filters::Base" do begin refute Haml::Filters.defined.has_key? "bar" Module.new {def self.name; "Foo::Bar"; end; include Haml::Filters::Base} assert Haml::Filters.defined.has_key? "bar" ensure Haml::Filters.remove_filter "Bar" end end test "should raise error when attempting to register a defined Tilt filter" do begin assert_raises RuntimeError do 2.times do Haml::Filters.register_tilt_filter "Foo" end end ensure Haml::Filters.remove_filter "Foo" end end test "should raise error when a Tilt filters dependencies are unavailable for extension" do begin assert_raises Haml::Error do Haml::Filters.register_tilt_filter "Textile" Haml::Filters.defined["textile"].template_class end ensure Haml::Filters.remove_filter "Textile" end end test "should raise error when a Tilt filters dependencies are unavailable for filter without extension" do begin assert_raises Haml::Error do Haml::Filters.register_tilt_filter "Maruku" Haml::Filters.defined["maruku"].template_class end ensure Haml::Filters.remove_filter "Maruku" end end test "should raise informative error about Maruku being moved to haml-contrib" do begin render(":maruku\n # foo") flunk("Should have raised error with message about the haml-contrib gem.") rescue Haml::Error => e assert_equal e.message, Haml::Error.message(:install_haml_contrib, "maruku") end end test "should raise informative error about Textile being moved to haml-contrib" do begin render(":textile\n h1. foo") flunk("Should have raised error with message about the haml-contrib gem.") rescue Haml::Error => e assert_equal e.message, Haml::Error.message(:install_haml_contrib, "textile") end end test "should respect escaped newlines and interpolation" do html = "\\n\n\n" haml = ":plain\n \\n\#{""}" assert_equal(html, render(haml)) end test "should process an filter with no content" do assert_equal("\n", render(':plain')) end test ":plain with content" do expectation = "foo\n" assert_equal(expectation, render(":plain\n foo")) end test "should pass options to Tilt filters that precompile" do begin orig_erb_opts = Haml::Filters::Erb.options haml = ":erb\n <%= 'foo' %>" refute_match('test_var', Haml::Engine.new(haml).compiler.precompiled) Haml::Filters::Erb.options = {:outvar => 'test_var'} assert_match('test_var', Haml::Engine.new(haml).compiler.precompiled) ensure Haml::Filters::Erb.options = orig_erb_opts end end test "should pass options to Tilt filters that don't precompile" do begin filter = Class.new(Tilt::Template) do def self.name "Foo" end def prepare @engine = {:data => data, :options => options} end def evaluate(scope, locals, &block) @output = @engine[:options].to_a.join end end Haml::Filters.register_tilt_filter "Foo", :template_class => filter Haml::Filters::Foo.options[:foo] = "bar" haml = ":foo" assert_equal "foobar\n", render(haml) ensure Haml::Filters.remove_filter "Foo" end end test "interpolated code should be escaped if escape_html is set" do assert_equal "<script>evil</script>\n\n", render(":plain\n \#{''}", :escape_html => true) end end class ErbFilterTest < Haml::TestCase test "multiline expressions should work" do html = "foobarbaz\n\n" haml = %Q{:erb\n <%= "foo" +\n "bar" +\n "baz" %>} assert_equal(html, render(haml)) end test "should evaluate in the same context as Haml" do haml = ":erb\n <%= foo %>" html = "bar\n\n" scope = Object.new.instance_eval {foo = "bar"; nil if foo; binding} assert_equal(html, render(haml, :scope => scope)) end end class JavascriptFilterTest < Haml::TestCase test "should interpolate" do scope = Object.new.instance_eval {foo = "bar"; nil if foo; binding} haml = ":javascript\n \#{foo}" html = render(haml, :scope => scope) assert_match(/bar/, html) end test "should never HTML-escape non-interpolated ampersands" do html = "\n" haml = %Q{:javascript\n & < > \#{"&"}} assert_equal(html, render(haml, :escape_html => true)) end test "should not include type in HTML 5 output" do html = "\n" haml = ":javascript\n foo bar" assert_equal(html, render(haml, :format => :html5)) end test "should always include CDATA when format is xhtml" do html = "\n" haml = ":javascript\n foo bar" assert_equal(html, render(haml, :format => :xhtml, :cdata => false)) end test "should omit CDATA when cdata option is false" do html = "\n" haml = ":javascript\n foo bar" assert_equal(html, render(haml, :format => :html5, :cdata => false)) end test "should include CDATA when cdata option is true" do html = "\n" haml = ":javascript\n foo bar" assert_equal(html, render(haml, :format => :html5, :cdata => true)) end test "should default to no CDATA when format is html5" do haml = ":javascript\n foo bar" out = render(haml, :format => :html5) refute_match('//', out) end test "should emit tag on empty block" do html = "\n" haml = ":javascript" assert_equal(html, render(haml)) end end class CSSFilterTest < Haml::TestCase test "should wrap output in CDATA and a CSS tag when output is XHTML" do html = "\n" haml = ":css\n foo" assert_equal(html, render(haml, :format => :xhtml)) end test "should not include type in HTML 5 output" do html = "\n" haml = ":css\n foo bar" assert_equal(html, render(haml, :format => :html5)) end test "should always include CDATA when format is xhtml" do html = "\n" haml = ":css\n foo bar" assert_equal(html, render(haml, :format => :xhtml, :cdata => false)) end test "should omit CDATA when cdata option is false" do html = "\n" haml = ":css\n foo bar" assert_equal(html, render(haml, :format => :html5, :cdata => false)) end test "should include CDATA when cdata option is true" do html = "\n" haml = ":css\n foo bar" assert_equal(html, render(haml, :format => :html5, :cdata => true)) end test "should default to no CDATA when format is html5" do haml = ":css\n foo bar" out = render(haml, :format => :html5) refute_match('', out) end test "should emit tag on empty block" do html = "\n" haml = ":css" assert_equal(html, render(haml)) end end class CDATAFilterTest < Haml::TestCase test "should wrap output in CDATA tag" do html = "\n" haml = ":cdata\n foo" assert_equal(html, render(haml)) end end class EscapedFilterTest < Haml::TestCase test "should escape ampersands" do html = "&\n" haml = ":escaped\n &" assert_equal(html, render(haml)) end end class RubyFilterTest < Haml::TestCase test "can write to haml_io" do haml = ":ruby\n haml_io.puts 'hello'\n" html = "hello\n" assert_equal(html, render(haml)) end test "haml_io appends to output" do haml = "hello\n:ruby\n haml_io.puts 'hello'\n" html = "hello\nhello\n" assert_equal(html, render(haml)) end test "can create local variables" do haml = ":ruby\n a = 7\n=a" html = "7\n" assert_equal(html, render(haml)) end test "can render empty filter" do haml = ":ruby\n%foo" html = "\n" assert_equal(html, render(haml)) end end haml-5.1.2/test/gemfiles/000077500000000000000000000000001352226600500152135ustar00rootroot00000000000000haml-5.1.2/test/gemfiles/.bundle/000077500000000000000000000000001352226600500165425ustar00rootroot00000000000000haml-5.1.2/test/gemfiles/.bundle/config000066400000000000000000000000071352226600500177270ustar00rootroot00000000000000--- {} haml-5.1.2/test/gemfiles/Gemfile.rails-4.0.x000066400000000000000000000003431352226600500203640ustar00rootroot00000000000000source "https://rubygems.org" if ENV['TRAVIS'] platform :mri_21 do gem 'coveralls', require: false end end gem 'rails', '~> 4.0.0' gem 'nokogiri', RUBY_VERSION < '2.1' ? '~> 1.6.0' : '>= 1.7' gemspec :path => '../..' haml-5.1.2/test/gemfiles/Gemfile.rails-4.1.x000066400000000000000000000002151352226600500203630ustar00rootroot00000000000000source "https://rubygems.org" gem 'rails', '~> 4.1.0' gem 'nokogiri', RUBY_VERSION < '2.1' ? '~> 1.6.0' : '>= 1.7' gemspec :path => '../..' haml-5.1.2/test/gemfiles/Gemfile.rails-4.2.x000066400000000000000000000002151352226600500203640ustar00rootroot00000000000000source "https://rubygems.org" gem 'rails', '~> 4.2.0' gem 'nokogiri', RUBY_VERSION < '2.1' ? '~> 1.6.0' : '>= 1.7' gemspec :path => '../..' haml-5.1.2/test/gemfiles/Gemfile.rails-5.0.x000066400000000000000000000001201352226600500203560ustar00rootroot00000000000000source "https://rubygems.org" gem 'rails', '~> 5.0.0' gemspec :path => '../..' haml-5.1.2/test/gemfiles/Gemfile.rails-5.0.x.erubi000066400000000000000000000001341352226600500214700ustar00rootroot00000000000000source "https://rubygems.org" gem 'rails', '~> 5.0.0' gem 'erubi' gemspec :path => '../..' haml-5.1.2/test/gemfiles/Gemfile.rails-5.1.x000066400000000000000000000001201352226600500203570ustar00rootroot00000000000000source "https://rubygems.org" gem 'rails', '~> 5.1.0' gemspec :path => '../..' haml-5.1.2/test/gemfiles/Gemfile.rails-5.2.x000066400000000000000000000001201352226600500203600ustar00rootroot00000000000000source "https://rubygems.org" gem 'rails', '~> 5.2.0' gemspec :path => '../..' haml-5.1.2/test/gemfiles/Gemfile.rails-6.0.x000066400000000000000000000001241352226600500203630ustar00rootroot00000000000000source "https://rubygems.org" gem 'rails', '~> 6.0.0.rc1' gemspec :path => '../..' haml-5.1.2/test/gemfiles/Gemfile.rails-edge000066400000000000000000000001531352226600500205200ustar00rootroot00000000000000source "https://rubygems.org" gem 'rails', git: 'https://github.com/rails/rails' gemspec :path => '../..' haml-5.1.2/test/haml-spec/000077500000000000000000000000001352226600500152715ustar00rootroot00000000000000haml-5.1.2/test/helper_test.rb000066400000000000000000000316531352226600500162730ustar00rootroot00000000000000# frozen_string_literal: true require 'test_helper' class HelperTest < Haml::TestCase def test_flatten assert_equal("FooBar", Haml::Helpers.flatten("FooBar")) assert_equal("FooBar", Haml::Helpers.flatten("Foo\rBar")) assert_equal("Foo Bar", Haml::Helpers.flatten("Foo\nBar")) assert_equal("Hello World! YOU ARE FLAT? OMGZ!", Haml::Helpers.flatten("Hello\nWorld!\nYOU ARE \rFLAT?\n\rOMGZ!")) end def test_list_of_should_render_correctly assert_equal("
      • 1
      • \n
      • 2
      • ", render("= list_of([1, 2]) do |i|\n = i")) assert_equal("
      • [1]
      • ", render("= list_of([[1]]) do |i|\n = i.inspect")) assert_equal("
      • \n

        Fee

        \n

        A word!

        \n
      • \n
      • \n

        Fi

        \n

        A word!

        \n
      • \n
      • \n

        Fo

        \n

        A word!

        \n
      • \n
      • \n

        Fum

        \n

        A word!

        \n
      • ", render("= list_of(['Fee', 'Fi', 'Fo', 'Fum']) do |title|\n %h1= title\n %p A word!")) assert_equal("
      • \n a\n \n a\n
      • \n
      • \n a\n \n a\n
      • ", render("= list_of(['Fee', 'Fi']) do |title|\n %f>= \"a\\n\\na\"")) assert_equal("
      • 1
      • \n
      • 2
      • ", render("= list_of([1, 2], {:c => 3}) do |i|\n = i")) assert_equal("
      • [1]
      • ", render("= list_of([[1]], {:c => 3}) do |i|\n = i.inspect")) assert_equal("
      • \n

        Fee

        \n

        A word!

        \n
      • \n
      • \n

        Fi

        \n

        A word!

        \n
      • \n
      • \n

        Fo

        \n

        A word!

        \n
      • \n
      • \n

        Fum

        \n

        A word!

        \n
      • ", render("= list_of(['Fee', 'Fi', 'Fo', 'Fum'], {:c => 3}) do |title|\n %h1= title\n %p A word!")) end def test_buffer_access assert(render("= buffer") =~ /#/) assert_equal(render("= (buffer == _hamlout)"), "true\n") end def test_tabs assert_equal("foo\nbar\nbaz\n", render("foo\n- tab_up\nbar\n- tab_down\nbaz")) assert_equal("

        tabbed

        \n", render("- buffer.tabulation=5\n%p tabbed")) end def test_with_tabs assert_equal(<") rescue NoMethodError, ActionView::Template::Error proper_behavior = true end assert(proper_behavior) begin action_view_instance.render(inline: "<%= concat('foo') %>") rescue ArgumentError, NameError proper_behavior = true end assert(proper_behavior) end def test_action_view_included assert(Haml::Helpers.action_view?) end def test_capture_haml assert_equal(<13

        \\n" HTML - (foo = capture_haml(13) do |a| %p= a - end) = foo.inspect HAML end def test_haml_tag_name_attribute_with_id assert_equal("

        \n", render("- haml_tag 'p#some_id'")) end def test_haml_tag_name_attribute_with_colon_id assert_equal("

        \n", render("- haml_tag 'p#some:id'")) end def test_haml_tag_without_name_but_with_id assert_equal("
        \n", render("- haml_tag '#some_id'")) end def test_haml_tag_without_name_but_with_class assert_equal("
        \n", render("- haml_tag '.foo'")) end def test_haml_tag_without_name_but_with_colon_class assert_equal("
        \n", render("- haml_tag '.foo:bar'")) end def test_haml_tag_name_with_id_and_class assert_equal("

        \n", render("- haml_tag 'p#some_id.foo'")) end def test_haml_tag_name_with_class assert_equal("

        \n", render("- haml_tag 'p.foo'")) end def test_haml_tag_name_with_class_and_id assert_equal("

        \n", render("- haml_tag 'p.foo#some_id'")) end def test_haml_tag_name_with_id_and_multiple_classes assert_equal("

        \n", render("- haml_tag 'p#some_id.foo.bar'")) end def test_haml_tag_name_with_multiple_classes_and_id assert_equal("

        \n", render("- haml_tag 'p.foo.bar#some_id'")) end def test_haml_tag_name_and_attribute_classes_merging_with_id assert_equal("

        \n", render("- haml_tag 'p#some_id.foo', :class => 'bar'")) end def test_haml_tag_name_and_attribute_classes_merging assert_equal("

        \n", render("- haml_tag 'p.foo', :class => 'bar'")) end def test_haml_tag_name_merges_id_and_attribute_id assert_equal("

        \n", render("- haml_tag 'p#foo', :id => 'bar'")) end def test_haml_tag_attribute_html_escaping assert_equal("

        baz

        \n", render("%p{:id => 'foo&bar'} baz", :escape_html => true)) end def test_haml_tag_autoclosed_tags_are_closed_xhtml assert_equal("
        \n", render("- haml_tag :br, :class => 'foo'", :format => :xhtml)) end def test_haml_tag_autoclosed_tags_are_closed_html assert_equal("
        \n", render("- haml_tag :br, :class => 'foo'", :format => :html5)) end def test_haml_tag_with_class_array assert_equal("

        foo

        \n", render("- haml_tag :p, 'foo', :class => %w[a b]")) assert_equal("

        foo

        \n", render("- haml_tag 'p.c.d', 'foo', :class => %w[a b]")) end def test_haml_tag_with_id_array assert_equal("

        foo

        \n", render("- haml_tag :p, 'foo', :id => %w[a b]")) assert_equal("

        foo

        \n", render("- haml_tag 'p#c', 'foo', :id => %w[a b]")) end def test_haml_tag_with_data_hash assert_equal("

        foo

        \n", render("- haml_tag :p, 'foo', :data => {:foo => 'bar', :baz => true}")) end def test_haml_tag_non_autoclosed_tags_arent_closed assert_equal("

        \n", render("- haml_tag :p")) end def test_haml_tag_renders_text_on_a_single_line assert_equal("

        #{'a' * 100}

        \n", render("- haml_tag :p, 'a' * 100")) end def test_haml_tag_raises_error_for_multiple_content assert_raises(Haml::Error) { render("- haml_tag :p, 'foo' do\n bar") } end def test_haml_tag_flags assert_equal("

        \n", render("- haml_tag :p, :/", :format => :xhtml)) assert_equal("

        \n", render("- haml_tag :p, :/", :format => :html5)) assert_equal("

        kumquat

        \n", render("- haml_tag :p, :< do\n kumquat")) assert_raises(Haml::Error) { render("- haml_tag :p, 'foo', :/") } assert_raises(Haml::Error) { render("- haml_tag :p, :/ do\n foo") } end def test_haml_tag_error_return assert_raises(Haml::Error) { render("= haml_tag :p") } end def test_haml_tag_with_multiline_string assert_equal(< foo bar baz

        HTML - haml_tag :p, "foo\\nbar\\nbaz" HAML end def test_haml_concat_with_multiline_string assert_equal(< foo bar baz

        HTML %p - haml_concat "foo\\nbar\\nbaz" HAML end def test_haml_tag assert_equal(< Hi!

        HTML - haml_tag :p do - haml_tag :strong, "Hi!" HAML end def test_haml_tag_if_positive assert_equal(<

        A para

    HTML - haml_tag_if true, '.conditional' do %p A para HAML end def test_haml_tag_if_positive_with_attributes assert_equal(<

    A para

    HTML - haml_tag_if true, '.conditional', {:foo => 'bar'} do %p A para HAML end def test_haml_tag_if_negative assert_equal(<A para

    HTML - haml_tag_if false, '.conditional' do %p A para HAML end def test_haml_tag_if_error_return assert_raises(Haml::Error) { render("= haml_tag_if false, '.conditional' do\n %p Hello") } end def test_is_haml assert(!ActionView::Base.new(ActionView::LookupContext.new('')).is_haml?) assert_equal("true\n", render("= is_haml?")) end def test_capture_deals_properly_with_collections obj = Object.new def obj.trc(collection, &block) collection.each do |record| haml_concat capture_haml(record, &block) end end assert_equal("1\n\n2\n\n3\n\n", render("- trc([1, 2, 3]) do |i|\n = i.inspect", scope: obj)) end def test_find_and_preserve_with_block assert_equal("
    Foo
    Bar
    \nFoo\nBar\n", render("= find_and_preserve do\n %pre\n Foo\n Bar\n Foo\n Bar")) end def test_find_and_preserve_with_block_and_tags assert_equal("
    Foo\nBar
    \nFoo\nBar\n", render("= find_and_preserve([]) do\n %pre\n Foo\n Bar\n Foo\n Bar")) end def test_preserve_with_block assert_equal("
    Foo
    Bar
    Foo Bar", render("= preserve do\n %pre\n Foo\n Bar\n Foo\n Bar")) end def test_init_haml_helpers context = Object.new class << context include Haml::Helpers end context.init_haml_helpers result = context.capture_haml do context.haml_tag :p, :attr => "val" do context.haml_concat "Blah" end end assert_equal("

    \n Blah\n

    \n", result) end def test_non_haml assert_equal("false\n", render("= non_haml { is_haml? }")) end def test_error_return assert_raises(Haml::Error, < e assert_equal 2, e.backtrace[0].scan(/:(\d+)/).first.first.to_i end def test_error_return_line_in_helper obj = Object.new def obj.something_that_uses_haml_concat haml_concat('foo').to_s end render("- something_that_uses_haml_concat", scope: obj) assert false, "Expected Haml::Error" rescue Haml::Error => e assert_equal __LINE__ - 6, e.backtrace[0].scan(/:(\d+)/).first.first.to_i end def test_html_escape assert_equal ""><&", Haml::Helpers.html_escape('"><&') end def test_html_escape_should_work_on_frozen_strings assert Haml::Helpers.html_escape('foo'.freeze) rescue => e flunk e.message end def test_html_escape_encoding old_stderr, $stderr = $stderr, StringIO.new string = "\"><&\u00e9" # if you're curious, u00e9 is "LATIN SMALL LETTER E WITH ACUTE" assert_equal ""><&\u00e9", Haml::Helpers.html_escape(string) assert $stderr.string == "", "html_escape shouldn't generate warnings with UTF-8 strings: #{$stderr.string}" ensure $stderr = old_stderr end def test_html_escape_non_string assert_equal('4.58', Haml::Helpers.html_escape(4.58)) assert_equal('4.58', Haml::Helpers.html_escape_without_haml_xss(4.58)) end def test_escape_once assert_equal ""><&", Haml::Helpers.escape_once('"><&') end def test_escape_once_leaves_entity_references assert_equal ""><&  ", Haml::Helpers.escape_once('"><&  ') end def test_escape_once_leaves_numeric_references assert_equal ""><&  ", Haml::Helpers.escape_once('"><&  ') #decimal assert_equal ""><&  ", Haml::Helpers.escape_once('"><&  ') #hexadecimal end def test_escape_once_encoding old_stderr, $stderr = $stderr, StringIO.new string = "\"><&\u00e9  " assert_equal ""><&\u00e9  ", Haml::Helpers.escape_once(string) assert $stderr.string == "", "html_escape shouldn't generate warnings with UTF-8 strings: #{$stderr.string}" ensure $stderr = old_stderr end def test_html_attrs_xhtml assert_equal("\n", render("%html{html_attrs}", :format => :xhtml)) end def test_html_attrs_html4 assert_equal("\n", render("%html{html_attrs}", :format => :html4)) end def test_html_attrs_html5 assert_equal("\n", render("%html{html_attrs}", :format => :html5)) end def test_html_attrs_xhtml_other_lang assert_equal("\n", render("%html{html_attrs('es-AR')}", :format => :xhtml)) end def test_html_attrs_html4_other_lang assert_equal("\n", render("%html{html_attrs('es-AR')}", :format => :html4)) end def test_html_attrs_html5_other_lang assert_equal("\n", render("%html{html_attrs('es-AR')}", :format => :html5)) end def test_escape_once_should_work_on_frozen_strings Haml::Helpers.escape_once('foo'.freeze) rescue => e flunk e.message end end haml-5.1.2/test/helpers_for_rails_test.rb000066400000000000000000000205631352226600500205140ustar00rootroot00000000000000# frozen_string_literal: true require 'test_helper' require "active_model/naming" class HelpersForRailsTest < Haml::TestCase class FormModel extend ActiveModel::Naming end TEXT_AREA_CONTENT_REGEX = /<(textarea)[^>]*>\n(.*?)<\/\1>/im Post = Struct.new('Post', :body, :error_field, :errors) class PostErrors def on(name) return unless name == 'error_field' ["Really bad error"] end alias_method :full_messages, :on def [](name) on(name) || [] end end def setup context = ActionView::LookupContext.new(File.expand_path("../templates", __FILE__)) @base = Class.new(ActionView::Base) { def nested_tag content_tag(:span) {content_tag(:div) {"something"}} end def wacky_form form_tag("/foo") {"bar"} end }.new(context, {post: Post.new("Foo bar\nbaz", nil, PostErrors.new)}, ActionController::Base.new) end def render(text, options = {}) return @base.render :inline => text, :type => :haml if options == :action_view super end def test_rendering_with_escapes def @base.render_something_with_haml_concat haml_concat "

    " end def @base.render_something_with_haml_tag_and_concat haml_tag 'p' do haml_concat '' end end output = render(<<-HAML, :action_view) - render_something_with_haml_concat - render_something_with_haml_tag_and_concat - render_something_with_haml_concat HAML assert_equal("<p>\n

    \n <foo>\n

    \n<p>\n", output) end def test_with_raw_haml_concat haml = <&" HAML assert_equal("<>&\n", render(haml, :action_view)) end def test_form_tag def @base.protect_against_forgery?; false; end rendered = render(<]+>Foo bar baz\n), render('= content_tag "pre", "Foo bar\n baz"', :action_view)) end def test_text_area_tag output = render('= text_area_tag "body", "Foo\nBar\n Baz\n Boom"', :action_view) match_data = output.match(TEXT_AREA_CONTENT_REGEX) assert_equal "Foo Bar Baz Boom", match_data[2] end def test_text_area output = render('= text_area :post, :body', :action_view) match_data = output.match(TEXT_AREA_CONTENT_REGEX) assert_equal "Foo bar baz", match_data[2] end def test_partials_should_not_cause_textareas_to_be_indented # non-indentation of textareas rendered inside partials @base.instance_variable_set(:@post, Post.new("Foo", nil, PostErrors.new)) output = render(".foo\n .bar\n = render '/text_area_helper'", :action_view) match_data = output.match(TEXT_AREA_CONTENT_REGEX) assert_equal 'Foo', match_data[2] end def test_textareas_should_preserve_leading_whitespace # leading whitespace preservation @base.instance_variable_set(:@post, Post.new(" Foo", nil, PostErrors.new)) output = render(".foo\n = text_area :post, :body", :action_view) match_data = output.match(TEXT_AREA_CONTENT_REGEX) assert_equal ' Foo', match_data[2] end def test_textareas_should_preserve_leading_whitespace_in_partials # leading whitespace in textareas rendered inside partials @base.instance_variable_set(:@post, Post.new(" Foo", nil, PostErrors.new)) output = render(".foo\n .bar\n = render '/text_area_helper'", :action_view) match_data = output.match(TEXT_AREA_CONTENT_REGEX) assert_equal ' Foo', match_data[2] end def test_content_tag_block assert_equal(<

    bar

    bar
    HTML = content_tag :div do %p bar %strong bar HAML end def test_content_tag_error_wrapping def @base.protect_against_forgery?; false; end output = render(< :post, :html => {:class => nil, :id => nil}, :url => '' do |f| = f.label 'error_field' HAML fragment = Nokogiri::HTML.fragment(output) refute_nil fragment.css('form div.field_with_errors label[for=post_error_field]').first end def test_form_tag_in_helper_with_string_block def @base.protect_against_forgery?; false; end rendered = render('= wacky_form', :action_view) fragment = Nokogiri::HTML.fragment(rendered) assert_equal 'bar', fragment.text.strip assert_equal '/foo', fragment.css('form').first.attributes['action'].to_s end def test_haml_concat_inside_haml_tag_escaped_with_xss assert_equal("

    \n <>&\n

    \n", render(<&" HAML end def test_is_haml assert(!ActionView::Base.new(ActionView::LookupContext.new('')).is_haml?) assert_equal("true\n", render("= is_haml?", :action_view)) assert_equal("false", @base.render(:inline => '<%= is_haml? %>')) assert_equal("false\n", render("= render :inline => '<%= is_haml? %>'", :action_view)) end def test_page_class controller = Struct.new(:controller_name, :action_name).new('troller', 'tion') scope = Struct.new(:controller).new(controller) result = render("%div{:class => page_class} MyDiv", :scope => scope) expected = "
    MyDiv
    \n" assert_equal expected, result end def test_indented_capture assert_equal(" Foo\n ", @base.render(:inline => " <% res = capture do %>\n Foo\n <% end %><%= res %>")) end def test_capture_with_string_block assert_equal("foo\n", render("= capture { 'foo' }", :action_view)) end def test_capture_with_non_string_value_returns_nil def @base.check_capture_returns_nil(&block) contents = capture(&block) contents << "ERROR" if contents end assert_equal("\n", render("= check_capture_returns_nil { 2 }", :action_view)) end class HomemadeViewContext include ActionView::Context include ActionView::Helpers::FormHelper def initialize _prepare_context end def url_for(*) "/" end def dom_class(*) end def dom_id(*) end def m # I have to inject the model into the view using an instance method, using locals doesn't work. FormModel.new end def protect_against_forgery? end def compiled_method_container self.class end def _run(method, template, locals, buffer, &block) @current_template = template @output_buffer = buffer send(method, locals, buffer, &block) end # def capture(*args, &block) # capture_haml(*args, &block) # end end def test_form_for_with_homemade_view_context handler = ActionView::Template.handler_for_extension("haml") template = ActionView::Template.new(< "/") do %b Bold! HAML # see if Bold is within form tags: assert_match(/.*Bold!<\/b>.*<\/form>/m, template.render(HomemadeViewContext.new, {})) end def test_content_tag_nested assert_equal "
    something
    ", render("= nested_tag", :action_view).strip end class ActsLikeTag # We want to be able to have people include monkeypatched ActionView helpers # without redefining is_haml?. # This is accomplished via Object#is_haml?, and this is a test for it. include ActionView::Helpers::TagHelper def to_s content_tag :p, 'some tag content' end end def test_random_class_includes_tag_helper assert_equal "

    some tag content

    ", ActsLikeTag.new.to_s end def test_capture_with_nuke_outer assert_equal "
    \n*
    hi there!
    \n", render(< hi there! HAML assert_equal "
    \n*
    hi there!
    \n", render(< hi there! HAML end end haml-5.1.2/test/markaby/000077500000000000000000000000001352226600500150465ustar00rootroot00000000000000haml-5.1.2/test/markaby/standard.mab000066400000000000000000000036701352226600500173350ustar00rootroot00000000000000self << '' html(:xmlns=>'http://www.w3.org/1999/xhtml', 'xml:lang'=>'en-US') do head do title "Hampton Catlin Is Totally Awesome" meta("http-equiv" => "Content-Type", :content => "text/html; charset=utf-8") end body do # You're In my house now! div :class => "header" do self << %|Yes, ladies and gentileman. He is just that egotistical. Fantastic! This should be multi-line output The question is if this would translate! Ahah!| self << 1 + 9 + 8 + 2 #numbers should work and this should be ignored end div(:id => "body") { self << "Quotes should be loved! Just like people!"} 120.times do |number| number end self << "Wow.|" p do self << "Holy cow " + "multiline " + "tags! " + "A pipe (|) even!" self << [1, 2, 3].collect { |n| "PipesIgnored|" } self << [1, 2, 3].collect { |n| n.to_s }.join("|") end div(:class => "silent") do foo = String.new foo << "this" foo << " shouldn't" foo << " evaluate" self << foo + " but now it should!" # Woah crap a comment! end # That was a line that shouldn't close everything. ul(:class => "really cool") do ('a'..'f').each do |a| li a end end div((@should_eval = "with this text"), :id => "combo", :class => "of_divs_with_underscore") [ 104, 101, 108, 108, 111 ].map do |byte| byte.chr end div(:class => "footer") do strong("This is a really long ruby quote. It should be loved and wrapped because its more than 50 characters. This value may change in the future and this test may look stupid. \nSo, I'm just making it *really* long. God, I hope this works", :class => "shout") end end end haml-5.1.2/test/mocks/000077500000000000000000000000001352226600500145345ustar00rootroot00000000000000haml-5.1.2/test/mocks/article.rb000066400000000000000000000002301352226600500164770ustar00rootroot00000000000000# frozen_string_literal: true class Article attr_accessor :id, :title, :body def initialize @id, @title, @body = 1, 'Hello', 'World' end end haml-5.1.2/test/options_test.rb000066400000000000000000000013501352226600500164760ustar00rootroot00000000000000# frozen_string_literal: true require 'test_helper' module Haml class OptionsTest < Haml::TestCase def test_buffer_defaults_have_only_buffer_option_keys assert_equal( Haml::Options.buffer_option_keys.sort, Haml::Options.buffer_defaults.keys.sort, ) end def test_buffer_defaults_values_are_the_same_as_rails_defaults rails_defaults = Haml::Options.defaults.merge(Haml::Template.options) Haml::Options.buffer_option_keys.each do |key| if rails_defaults[key].nil? assert_nil Haml::Options.buffer_defaults[key], "key: #{key}" else assert_equal rails_defaults[key], Haml::Options.buffer_defaults[key], "key: #{key}" end end end end end haml-5.1.2/test/parser_test.rb000066400000000000000000000132011352226600500162750ustar00rootroot00000000000000# frozen_string_literal: true require 'test_helper' module Haml class ParserTest < Haml::TestCase test "should raise error for 'else' at wrong indent level" do begin parse("- if true\n #first\n text\n - else\n #second") flunk("Should have raised a Haml::SyntaxError") rescue SyntaxError => e assert_equal Error.message(:bad_script_indent, 'else', 0, 1), e.message end end test "should raise error for 'elsif' at wrong indent level" do begin parse("- if true\n #first\n text\n - elsif false\n #second") flunk("Should have raised a Haml::SyntaxError") rescue SyntaxError => e assert_equal Error.message(:bad_script_indent, 'elsif', 0, 1), e.message end end test "should raise error for 'else' at wrong indent level after unless" do begin parse("- unless true\n #first\n text\n - else\n #second") flunk("Should have raised a Haml::SyntaxError") rescue SyntaxError => e assert_equal Error.message(:bad_script_indent, 'else', 0, 1), e.message end end test "should raise syntax error for else with no if" do begin parse("- else\n 'foo'") flunk("Should have raised a Haml::SyntaxError") rescue SyntaxError => e assert_equal Error.message(:missing_if, 'else'), e.message end end test "should raise syntax error for nested else with no" do begin parse("#foo\n - else\n 'foo'") flunk("Should have raised a Haml::SyntaxError") rescue SyntaxError => e assert_equal Error.message(:missing_if, 'else'), e.message end end test "else after if containing case is accepted" do # see issue 572 begin parse "- if true\n - case @foo\n - when 1\n bar\n- else\n bar" assert true rescue SyntaxError flunk 'else clause after if containing case should be accepted' end end test "else after if containing unless is accepted" do begin parse "- if true\n - unless @foo\n bar\n- else\n bar" assert true rescue SyntaxError flunk 'else clause after if containing unless should be accepted' end end test "loud script with else is accepted" do begin parse "= if true\n - 'A'\n-else\n - 'B'" assert true rescue SyntaxError flunk 'loud script (=) should allow else' end end test "else after nested loud script is accepted" do begin parse "-if true\n =if true\n - 'A'\n-else\n B" assert true rescue SyntaxError flunk 'else after nested loud script should be accepted' end end test "case with indented whens should allow else" do begin parse "- foo = 1\n-case foo\n -when 1\n A\n -else\n B" assert true rescue SyntaxError flunk 'case with indented whens should allow else' end end test "inspect for node with children returns text" do text = "some revealed text" cond = "[cond]" node = parse("/!#{cond} #{text}") assert_equal "(root nil\n (comment {:conditional=>\"[cond]\", :text=>\"some revealed text\", :revealed=>true, :parse=>false}))", node.inspect end test "revealed conditional comments are detected" do text = "some revealed text" cond = "[cond]" node = parse("/!#{cond} #{text}").children[0] assert_equal text, node.value[:text] assert_equal cond, node.value[:conditional] assert node.value[:revealed] end test "hidden conditional comments are detected" do text = "some revealed text" cond = "[cond]" node = parse("/#{cond} #{text}").children[0] assert_equal text, node.value[:text] assert_equal cond, node.value[:conditional] refute node.value[:revealed] end test "only script lines are checked for continuation keywords" do haml = "- if true\n setup\n- else\n else\n" node = parse(haml).children[0] assert_equal(3, node.children.size) end # see #830. Strictly speaking the pipe here is not necessary, but there # shouldn't be an error if it is there. test "multiline Ruby with extra trailing pipe doesn't raise error" do haml = "%p= foo bar, |\n baz" begin parse haml rescue Haml::SyntaxError flunk "Should not have raised SyntaxError" end end test "empty filter doesn't hide following lines" do root = parse "%p\n :plain\n %p\n" p_element = root.children[0] assert_equal 2, p_element.children.size assert_equal :filter, p_element.children[0].type assert_equal :tag, p_element.children[1].type end # Previously blocks under a haml_comment would be rejected if any line was # indented by a value that wasn't a multiple of the document indentation. test "haml_comment accepts any indentation in content" do begin parse "-\#\n Indented two spaces\n Indented three spaces" rescue Haml::SyntaxError flunk "haml_comment should accept any combination of indentation" end end test "block haml_comment includes text" do root = parse "-#\n Hello\n Hello\n" assert_equal "Hello\n Hello\n", root.children[0].value[:text] end test "block haml_comment includes first line if present" do root = parse "-# First line\n Hello\n Hello\n" assert_equal " First line\nHello\n Hello\n", root.children[0].value[:text] end private def parse(haml, options = nil) options ||= Options.new parser = Parser.new(options) parser.call(haml) end end end haml-5.1.2/test/results/000077500000000000000000000000001352226600500151215ustar00rootroot00000000000000haml-5.1.2/test/results/bemit.xhtml000066400000000000000000000002541352226600500173000ustar00rootroot00000000000000

    ...

    haml-5.1.2/test/results/content_for_layout.xhtml000066400000000000000000000004571352226600500221220ustar00rootroot00000000000000
    Lorem ipsum dolor sit amet
    Lorem ipsum dolor sit amet
    haml-5.1.2/test/results/eval_suppressed.xhtml000066400000000000000000000001641352226600500214040ustar00rootroot00000000000000

    Me!

    All


    This

    Should render
    haml-5.1.2/test/results/helpers.xhtml000066400000000000000000000017521352226600500176460ustar00rootroot00000000000000&&&&&&&&&&&

    Title

    Woah this is really crazy I mean wow, man.

    Title

    Woah this is really crazy I mean wow, man.

    Title

    Woah this is really crazy I mean wow, man.

    foo

    reeeeeeeeeeeeeeeeeeeeeeeeeeeeeeally loooooooooooooooooong

    Big!

    Small

    foo

    bar

    (parentheses!)
    *Not really click here.

    baz

    boom

    foo
  • google
  • foo

    bar
    boom baz boom, again

    strong! data more_data

    haml-5.1.2/test/results/helpful.xhtml000066400000000000000000000006411352226600500176370ustar00rootroot00000000000000

    Hello

    World
    id
    class
    id class
    boo
    moo
    foo
    Boo haml-5.1.2/test/results/just_stuff.xhtml000066400000000000000000000037531352226600500204030ustar00rootroot00000000000000 Boo! Embedded? false! Embedded? true! Embedded? true! Embedded? twice! true! Embedded? one af"t"er another!

    Embedded? false!

    Embedded? true!

    Embedded? true!

    Embedded? twice! true!

    Embedded? one af"t"er another!

    stuff followed by whitespace block with whitespace

    Escape - character %p foo yee\ha don't lstrip me

    class attribute should appear!

    this attribute shouldn't appear

    testtest


    Nested content

    Blah

    Blah

    Blah

    Blump

    Whee

    Woah inner quotes

    hello

    haml-5.1.2/test/results/list.xhtml000066400000000000000000000001761352226600500171560ustar00rootroot00000000000000!Not a Doctype!
    • a
    • b
    • c
    • d
    • e
    • f
    • g
    • h
    • i
    haml-5.1.2/test/results/nuke_inner_whitespace.xhtml000066400000000000000000000004211352226600500225450ustar00rootroot00000000000000

    Foo

    Foo

    Foo Bar

    Foo Bar

    Foo Bar

    Foo Bar

    Foo Bar

    Foo Bar

    foo bar

    haml-5.1.2/test/results/nuke_outer_whitespace.xhtml000066400000000000000000000017201352226600500225730ustar00rootroot00000000000000

    Foo

    Foo

    Foo

    Foo

    Foo

    Foo

    Foo

    Foo

    Foo Bar

    Foo Bar

    Foo Bar

    Foo Bar

    foo Foo bar

    foo Foo bar

    fooFoobar

    fooFoobar

    foo Foo bar

    foo Foo bar

    fooFoobar

    fooFoobar

    foo Foo Bar bar

    foo Foo Bar bar

    fooFoo Barbar

    fooFoo Barbar

    haml-5.1.2/test/results/original_engine.xhtml000066400000000000000000000011051352226600500213250ustar00rootroot00000000000000 Stop. haml time

    This is a title!

    Lorem ipsum dolor sit amet, consectetur adipisicing elit

    Cigarettes!

    Man alive!

    • Slippers
    • Shoes
    • Bathrobe
    • Coffee
    This is some text that's in a pre block!
    Let's see what happens when it's rendered! What about now, since we're on a new line?
    haml-5.1.2/test/results/partial_layout.xhtml000066400000000000000000000002371352226600500212320ustar00rootroot00000000000000

    Partial layout used with for block:

    This is inside a partial layout

    Some content within a layout

    haml-5.1.2/test/results/partial_layout_erb.xhtml000066400000000000000000000002301352226600500220530ustar00rootroot00000000000000

    Partial layout used with for block:

    This is inside a partial layout

    Some content within a layout
    haml-5.1.2/test/results/partials.xhtml000066400000000000000000000002271352226600500200170ustar00rootroot00000000000000

    @foo = value one

    @foo = value two

    @foo = value two

    Toplevel? false

    @foo = value three

    @foo = value three

    haml-5.1.2/test/results/render_layout.xhtml000066400000000000000000000000241352226600500210470ustar00rootroot00000000000000Before During After haml-5.1.2/test/results/silent_script.xhtml000066400000000000000000000012711352226600500210620ustar00rootroot00000000000000

    I can count!

    1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

    I know my ABCs!

    • a
    • b
    • c
    • d
    • e
    • f
    • g
    • h
    • i
    • j
    • k
    • l
    • m
    • n
    • o
    • p
    • q
    • r
    • s
    • t
    • u
    • v
    • w
    • x
    • y
    • z

    I can catch errors!

    Oh no! "foo" happened!

    "false" is: false

    Even! Odd! Even! Odd! Even!
    foobar
    0 1 2 3 4

    boom

    haml-5.1.2/test/results/standard.xhtml000066400000000000000000000032111352226600500177740ustar00rootroot00000000000000 Hampton Catlin Is Totally Awesome
    Yes, ladies and gentileman. He is just that egotistical. Fantastic! This should be multi-line output The question is if this would translate! Ahah! 20
    Quotes should be loved! Just like people!
    0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 Wow.|

    Holy cow multiline tags! A pipe (|) even! PipesIgnored|PipesIgnored|PipesIgnored| 1|2|3

    this shouldn't evaluate but now it should!
    • a
    • b
    • c
    • d
    • e
    • f
    with this text
    foo haml-5.1.2/test/results/tag_parsing.xhtml000066400000000000000000000010031352226600500204670ustar00rootroot00000000000000
    1 2 3 4 5 6 7 8 9 10 11

    a
    b
    c
    d
    e
    f
    g
    haml-5.1.2/test/results/very_basic.xhtml000066400000000000000000000002451352226600500203260ustar00rootroot00000000000000 haml-5.1.2/test/results/whitespace_handling.xhtml000066400000000000000000000073651352226600500222120ustar00rootroot00000000000000
    Foo bar
    foo bar
    foo
    bar

    foo
    bar

    foo bar

    13
    Foo bar
    foo bar
    foo
    bar

    foo
    bar

    foo bar

                                                     ___
                                                  ,o88888
                                               ,o8888888'
                         ,:o:o:oooo.        ,8O88Pd8888"
                     ,.::.::o:ooooOoOoO. ,oO8O8Pd888'"
                   ,.:.::o:ooOoOoOO8O8OOo.8OOPd8O8O"
                  , ..:.::o:ooOoOOOO8OOOOo.FdO8O8"
                 , ..:.::o:ooOoOO8O888O8O,COCOO"
                , . ..:.::o:ooOoOOOO8OOOOCOCO"
                 . ..:.::o:ooOoOoOO8O8OCCCC"o
                    . ..:.::o:ooooOoCoCCC"o:o
                    . ..:.::o:o:,cooooCo"oo:o:
                 `   . . ..:.:cocoooo"'o:o:::'
                 .`   . ..::ccccoc"'o:o:o:::'
                :.:.    ,c:cccc"':.:.:.:.:.'
              ..:.:"'`::::c:"'..:.:.:.:.:.'  http://www.chris.com/ASCII/
            ...:.'.:.::::"'    . . . . .'
           .. . ....:."' `   .  . . ''
         . . . ...."'
         .. . ."'     -hrr-
        .
    
    
                                                  It's a planet!
    %strong This shouldn't be bold!
    This should!
    13
           __     ______        __               ______
    .----.|  |--.|__    |.----.|  |--..--------.|  __  |
    |  __||     ||__    ||  __||    < |        ||  __  |
    |____||__|__||______||____||__|__||__|__|__||______|
    foo
    bar
    haml-5.1.2/test/template_test.rb000066400000000000000000000236561352226600500166330ustar00rootroot00000000000000# frozen_string_literal: true require 'test_helper' require 'mocks/article' require 'action_pack/version' require 'template_test_helper' class TemplateTest < Haml::TestCase TEMPLATES = %w{ very_basic standard helpers whitespace_handling original_engine list helpful silent_script tag_parsing just_stuff partials nuke_outer_whitespace nuke_inner_whitespace bemit render_layout partial_layout partial_layout_erb}.freeze def setup @base = create_base # filters template uses :sass # Sass::Plugin.options.update(:line_comments => true, :style => :compact) end def create_base vars = { 'article' => Article.new, 'foo' => 'value one' } context = ActionView::LookupContext.new(TemplateTestHelper::TEMPLATE_PATH) base = ActionView::Base.new(context, vars) # This is needed by RJS in (at least) Rails 3 base.instance_variable_set(:@template, base) # This is used by form_for. # It's usually provided by ActionController::Base. def base.protect_against_forgery?; false; end def base.compiled_method_container() self.class; end base end def render(text, options = {}) return @base.render(:inline => text, :type => :haml) if options == :action_view options[:format] = :xhtml super(text, options, @base) end def load_result(name) @result = '' File.new(File.dirname(__FILE__) + "/results/#{name}.xhtml").each_line { |l| @result += l } @result end def assert_renders_correctly(name, &render_method) old_options = Haml::Template.options.dup Haml::Template.options[:escape_html] = false render_method ||= proc { |n| @base.render(template: n) } expected = load_result(name) actual = if ['silent_script', 'helpful'].include? name silence_warnings { render_method[name] } else render_method[name] end expected.split("\n").zip(actual.split("\n")).each_with_index do |pair, line| message = "template: #{name}\nline: #{line}" assert_equal(pair.first, pair.last, message) end rescue ActionView::Template::Error => e if e.message =~ /Can't run [\w:]+ filter; required (one of|file) ((?:'\w+'(?: or )?)+)(, but none were found| not found)/ puts "\nCouldn't require #{$2}; skipping a test." else raise e end ensure Haml::Template.options = old_options end def test_empty_render_should_remain_empty assert_equal('', render('')) end TEMPLATES.each do |template| define_method "test_template_should_render_correctly [template: #{template}]" do assert_renders_correctly template end end def test_render_method_returning_null @base.instance_eval do def empty nil end def render_something(&block) capture(self, &block) end end content_to_render = "%h1 This is part of the broken view.\n= render_something do |thing|\n = thing.empty do\n = 'test'" result = render(content_to_render) expected_result = "

    This is part of the broken view.

    \n" assert_equal(expected_result, result) end def test_simple_rendering content_to_render = "%p test\n= capture { 'foo' }" result = render(content_to_render) expected_result = "

    test

    \nfoo\n" assert_equal(expected_result, result) end def test_templates_should_render_correctly_with_render_proc assert_renders_correctly("standard") do |name| engine = Haml::Engine.new(File.read(File.dirname(__FILE__) + "/templates/#{name}.haml"), format: :xhtml) engine.render_proc(@base).call end end def test_templates_should_render_correctly_with_def_method assert_renders_correctly("standard") do |name| engine = Haml::Engine.new(File.read(File.dirname(__FILE__) + "/templates/#{name}.haml"), format: :xhtml) engine.def_method(@base, "render_standard") @base.render_standard end end def test_instance_variables_should_work_inside_templates @base.instance_variable_set(:@content_for_layout, 'something') assert_equal("

    something

    ", render("%p= @content_for_layout").chomp) @base.instance_eval("@author = 'Hampton Catlin'") assert_equal("
    Hampton Catlin
    ", render(".author= @author").chomp) @base.instance_eval("@author = 'Hampton'") assert_equal("Hampton", render("= @author").chomp) @base.instance_eval("@author = 'Catlin'") assert_equal("Catlin", render("= @author").chomp) end def test_precompiled_binary_frozen_string_works assert_equal("foo", ::Haml::Engine.new("foo", :encoding=>'BINARY').render(self, {}).chomp) end def test_instance_variables_should_work_inside_attributes @base.instance_eval("@author = 'hcatlin'") assert_equal("

    foo

    ", render("%p{:class => @author} foo").chomp) end def test_template_renders_should_eval assert_equal("2\n", render("= 1+1")) end def test_haml_options old_options = Haml::Template.options.dup Haml::Template.options[:suppress_eval] = true old_base, @base = @base, create_base assert_renders_correctly("eval_suppressed") ensure @base = old_base Haml::Template.options = old_options end def test_with_output_buffer assert_equal(< foo baz

    HTML %p foo -# Parenthesis required due to Rails 3.0 deprecation of block helpers -# that return strings. - (with_output_buffer do bar = "foo".gsub(/./) do |s| - "flup" - end) baz HAML end def test_exceptions_should_work_correctly begin render("- raise 'oops!'") rescue Exception => e assert_equal("oops!", e.message) assert_match(/^\(haml\):1/, e.backtrace[0]) else assert false end template = < e assert_match(/^\(haml\):5/, e.backtrace[0]) else assert false end end def test_form_builder_label_with_block output = render(< :article, :html => {:class => nil, :id => nil}, :url => '' do |f| = f.label :title do Block content HAML fragment = Nokogiri::HTML.fragment output assert_equal "Block content", fragment.css('form label').first.content.strip end ## XSS Protection Tests def test_escape_html_option_set assert Haml::Template.options[:escape_html] end def test_xss_protection assert_equal("Foo & Bar\n", render('= "Foo & Bar"', :action_view)) end def test_xss_protection_with_safe_strings assert_equal("Foo & Bar\n", render('= Haml::Util.html_safe("Foo & Bar")', :action_view)) end def test_xss_protection_with_bang assert_equal("Foo & Bar\n", render('!= "Foo & Bar"', :action_view)) end def test_xss_protection_in_interpolation assert_equal("Foo & Bar\n", render('Foo #{"&"} Bar', :action_view)) end def test_xss_protection_in_attributes assert_equal("
    \n", render('%div{ "data-html" => "bar" }', :action_view)) end def test_xss_protection_in_attributes_with_safe_strings assert_equal("
    \n", render('%div{ "data-html" => "bar".html_safe }', :action_view)) end def test_xss_protection_with_bang_in_interpolation assert_equal("Foo & Bar\n", render('! Foo #{"&"} Bar', :action_view)) end def test_xss_protection_with_safe_strings_in_interpolation assert_equal("Foo & Bar\n", render('Foo #{Haml::Util.html_safe("&")} Bar', :action_view)) end def test_xss_protection_with_mixed_strings_in_interpolation assert_equal("Foo & Bar & Baz\n", render('Foo #{Haml::Util.html_safe("&")} Bar #{"&"} Baz', :action_view)) end def test_xss_protection_with_erb_filter if defined?(Haml::SafeErubiTemplate) assert_equal("<img>\n\n", render(":erb\n <%= '' %>", :action_view)) assert_equal("\n\n", render(":erb\n <%= ''.html_safe %>", :action_view)) else # For Haml::SafeErubisTemplate assert_equal("<img>\n", render(":erb\n <%= '' %>", :action_view)) assert_equal("\n", render(":erb\n <%= ''.html_safe %>", :action_view)) end end def test_rendered_string_is_html_safe assert(render("Foo").html_safe?) end def test_rendered_string_is_html_safe_with_action_view assert(render("Foo", :action_view).html_safe?) end def test_xss_html_escaping_with_non_strings assert_equal("4\n", render("= html_escape(4)")) end def test_xss_protection_with_concat assert_equal("Foo & Bar", render('- concat "Foo & Bar"', :action_view)) end def test_xss_protection_with_concat_with_safe_string assert_equal("Foo & Bar", render('- concat(Haml::Util.html_safe("Foo & Bar"))', :action_view)) end def test_xss_protection_with_safe_concat assert_equal("Foo & Bar", render('- safe_concat "Foo & Bar"', :action_view)) end ## Regression def test_xss_protection_with_nested_haml_tag assert_equal(<
    • Content!
    HTML - haml_tag :div do - haml_tag :ul do - haml_tag :li, "Content!" HAML end if defined?(ActionView::Helpers::PrototypeHelper) def test_rjs assert_equal(<'; end; end class ::TosSafeObject; def to_s; '
    '.html_safe; end; end def test_object_that_returns_safe_buffer assert_equal("
    \n", render('= ::TosSafeObject.new', escape_html: true)) assert_equal("<hr>\n", render('= ::TosUnsafeObject.new', escape_html: true)) end end haml-5.1.2/test/template_test_helper.rb000066400000000000000000000010601352226600500201530ustar00rootroot00000000000000# frozen_string_literal: true module TemplateTestHelper TEMPLATE_PATH = File.join(__dir__, "templates") end module Haml::Helpers def test_partial(name, locals = {}) Haml::Engine.new(File.read(File.join(TemplateTestHelper::TEMPLATE_PATH, "_#{name}.haml")), Haml::Template.options).render(self, locals) end end class Egocentic def method_missing(*) self end end class DummyController attr_accessor :logger def initialize @logger = Egocentic.new end def self.controller_path '' end def controller_path '' end end haml-5.1.2/test/templates/000077500000000000000000000000001352226600500154165ustar00rootroot00000000000000haml-5.1.2/test/templates/_av_partial_1.haml000066400000000000000000000003351352226600500207630ustar00rootroot00000000000000%h2 This is a pretty complicated partial .partial %p It has several nested partials, %ul - 5.times do %li %strong Partial: - @nesting = 5 = render :partial => 'templates/av_partial_2'haml-5.1.2/test/templates/_av_partial_2.haml000066400000000000000000000002701352226600500207620ustar00rootroot00000000000000- @nesting -= 1 .partial{:level => @nesting} %h3 This is a crazy deep-nested partial. %p== Nesting level #{@nesting} = render :partial => 'templates/av_partial_2' if @nesting > 0haml-5.1.2/test/templates/_layout.erb000066400000000000000000000000331352226600500175600ustar00rootroot00000000000000Before <%= yield -%> After haml-5.1.2/test/templates/_layout_for_partial.haml000066400000000000000000000000771352226600500223230ustar00rootroot00000000000000.partial-layout %h2 This is inside a partial layout = yieldhaml-5.1.2/test/templates/_partial.haml000066400000000000000000000001511352226600500200510ustar00rootroot00000000000000%p @foo = = @foo - @foo = 'value three' == Toplevel? #{haml_buffer.toplevel?} %p @foo = = @foo haml-5.1.2/test/templates/_text_area.haml000066400000000000000000000001361352226600500203740ustar00rootroot00000000000000.text_area_test_area ~ "" = "" haml-5.1.2/test/templates/_text_area_helper.html.haml000066400000000000000000000001421352226600500226730ustar00rootroot00000000000000- defined?(text_area_helper) and nil # silence a warning .foo .bar = text_area :post, :body haml-5.1.2/test/templates/action_view.haml000066400000000000000000000033651352226600500205770ustar00rootroot00000000000000!!! %html{html_attrs} %head %title Hampton Catlin Is Totally Awesome %meta{"http-equiv" => "Content-Type", :content => "text/html; charset=utf-8"} %body %h1 This is very much like the standard template, except that it has some ActionView-specific stuff. It's only used for benchmarking. .crazy_partials= render :partial => 'templates/av_partial_1' / You're In my house now! .header Yes, ladies and gentileman. He is just that egotistical. Fantastic! This should be multi-line output The question is if this would translate! Ahah! = 1 + 9 + 8 + 2 #numbers should work and this should be ignored #body= " Quotes should be loved! Just like people!" - 120.times do |number| - number Wow.| %p = "Holy cow " + | "multiline " + | "tags! " + | "A pipe (|) even!" | = [1, 2, 3].collect { |n| "PipesIgnored|" } = [1, 2, 3].collect { |n| | n.to_s | }.join("|") | %div.silent - foo = String.new - foo << "this" - foo << " shouldn't" - foo << " evaluate" = foo + " but now it should!" -# Woah crap a comment! -# That was a line that shouldn't close everything. %ul.really.cool - ('a'..'f').each do |a| %li= a #combo.of_divs_with_underscore= @should_eval = "with this text" = [ 104, 101, 108, 108, 111 ].map do |byte| - byte.chr .footer %strong.shout= "This is a really long ruby quote. It should be loved and wrapped because its more than 50 characters. This value may change in the future and this test may look stupid. \nSo, I'm just making it *really* long. God, I hope this works" haml-5.1.2/test/templates/bemit.haml000066400000000000000000000002111352226600500173530ustar00rootroot00000000000000.o-media@md.c-user.c-user--premium %img.o-media__img@md.c-user__photo.c-avatar{src: '', alt: ''} %p.o-media__body@md.c-user__bio ... haml-5.1.2/test/templates/breakage.haml000066400000000000000000000001751352226600500200250ustar00rootroot00000000000000%p %h1 Hello! = "lots of lines" - raise "Oh no!" %p this is after the exception %strong yes it is! ho ho ho. haml-5.1.2/test/templates/content_for_layout.haml000066400000000000000000000001251352226600500221740ustar00rootroot00000000000000!!! %html %head %body #yieldy = yield :layout #nosym = yield haml-5.1.2/test/templates/eval_suppressed.haml000066400000000000000000000002131352226600500214610ustar00rootroot00000000000000= "not me!" = "nor me!" - haml_concat "not even me!" %p= "NO!" %p~ "UH-UH!" %h1 Me! #foo %p#bar All %br/ %p.baz This Should render haml-5.1.2/test/templates/helpers.haml000066400000000000000000000022611352226600500177240ustar00rootroot00000000000000= h("&&&&&&&&&&&") # This is an ActionView Helper... should load - foo = capture do # This ActionView Helper is designed for ERB, but should work with haml %div %p.title Title %p.text Woah this is really crazy I mean wow, man. - 3.times do = foo %p foo - tab_up %p reeeeeeeeeeeeeeeeeeeeeeeeeeeeeeally loooooooooooooooooong - tab_down .woah #funky = capture_haml do %div %h1 Big! %p Small / Invisible = capture do .dilly %p foo %h1 bar = surround '(', ')' do %strong parentheses! = precede '*' do %span.small Not really click = succeed '.' do %a{:href=>"thing"} here %p baz - haml_buffer.tabulation = 10 %p boom - concat "foo\n" - haml_buffer.tabulation = 0 = list_of({:google => 'http://www.google.com'}) do |name, link| %a{ :href => link }= name %p - haml_concat "foo" %div - haml_concat "bar" - haml_concat "boom" baz - haml_concat "boom, again" - haml_tag :table do - haml_tag :tr do - haml_tag :td, {:class => 'cell'} do - haml_tag :strong, "strong!" - haml_concat "data" - haml_tag :td do - haml_concat "more_data" - haml_tag :hr - haml_tag :div, '' haml-5.1.2/test/templates/helpful.haml000066400000000000000000000004651352226600500177250ustar00rootroot00000000000000%div[@article] %h1= @article.title %div= @article.body #id[@article] id .class[@article] class #id.class[@article] id class %div{:class => "article full"}[@article]= "boo" %div{'class' => "article full"}[@article]= "moo" %div.articleFull[@article]= "foo" %span[@not_a_real_variable_and_will_be_nil] Boo haml-5.1.2/test/templates/just_stuff.haml000066400000000000000000000032551352226600500204620ustar00rootroot00000000000000!!! XML !!! XML ISO-8859-1 !!! XML UtF-8 Foo bar !!! !!! 1.1 !!! 1.1 Strict !!! Strict foo bar !!! FRAMESET %strong{:apos => "Foo's bar!"} Boo! == Embedded? false! == Embedded? #{true}! - embedded = true == Embedded? #{embedded}! == Embedded? #{"twice! #{true}"}! == Embedded? #{"one"} af"t"er #{"another"}! %p== Embedded? false! %p== Embedded? #{true}! - embedded = true %p== Embedded? #{embedded}! %p== Embedded? #{"twice! #{true}"}! %p== Embedded? #{"one"} af"t"er #{"another"}! = "stuff followed by whitespace" - if true %strong block with whitespace %p \Escape \- character \%p foo \yee\ha \ don't lstrip me / Short comment / This is a block comment cool, huh? %strong there can even be sub-tags! = "Or script!" -# Haml comment -# Nested Haml comment - raise 'dead' %p{ :class => "" } class attribute should appear! %p{ :gorbachev => nil } this attribute shouldn't appear /[if lte IE6] conditional comment! /[if gte IE7] %p Block conditional comment %div %h1 Cool, eh? /[if gte IE5.2] Woah a period. = "test" | "test" | -# Hard tabs shouldn't throw errors. - case :foo - when :bar %br Blah - when :foo %br - case :foo - when :bar %meta{ :foo => 'blah'} - when :foo %meta{ :foo => 'bar'} %img %hr %link %script Inline content %br Nested content %p.foo{:class => true ? 'bar' : 'baz'}[@article] Blah %p.foo{:class => false ? 'bar' : ''}[@article] Blah %p.foo{:class => %w[bar baz]}[@article] Blah %p.qux{:class => 'quux'}[@article] Blump %p#foo{:id => %w[bar baz]}[@article] Whee == #{"Woah inner quotes"} %p.dynamic_quote{:quotes => "single '", :dyn => 1 + 2} %p.dynamic_self_closing{:dyn => 1 + 2}/ %body :plain hello %div %img haml-5.1.2/test/templates/list.haml000066400000000000000000000001351352226600500172330ustar00rootroot00000000000000!Not a Doctype! %ul %li a %li b %li c %li d %li e %li f %li g %li h %li i haml-5.1.2/test/templates/nuke_inner_whitespace.haml000066400000000000000000000004641352226600500226360ustar00rootroot00000000000000%p %q< Foo %p %q{:a => 1 + 1}< Foo %p %q<= "Foo\nBar" %p %q{:a => 1 + 1}<= "Foo\nBar" %p %q< Foo Bar %p %q{:a => 1 + 1}< Foo Bar %p %q< %div Foo Bar %p %q{:a => 1 + 1}< %div Foo Bar -# Regression test %p %q<= "foo" %q{:a => 1 + 1} bar haml-5.1.2/test/templates/nuke_outer_whitespace.haml000066400000000000000000000026201352226600500226550ustar00rootroot00000000000000%p %p %q> Foo %p %p %q{:a => 1 + 1}> Foo %p %p %q> Foo %p %p %q{:a => 1 + 1}> Foo %p %p %q> = "Foo" %p %p %q{:a => 1 + 1}> = "Foo" %p %p %q>= "Foo" %p %p %q{:a => 1 + 1}>= "Foo" %p %p %q> = "Foo\nBar" %p %p %q{:a => 1 + 1}> = "Foo\nBar" %p %p %q>= "Foo\nBar" %p %p %q{:a => 1 + 1}>= "Foo\nBar" %p %p - tab_up foo %q> Foo bar - tab_down %p %p - tab_up foo %q{:a => 1 + 1}> Foo bar - tab_down %p %p - tab_up foo %q> Foo bar - tab_down %p %p - tab_up foo %q{:a => 1 + 1}> Foo bar - tab_down %p %p - tab_up foo %q> = "Foo" bar - tab_down %p %p - tab_up foo %q{:a => 1 + 1}> = "Foo" bar - tab_down %p %p - tab_up foo %q>= "Foo" bar - tab_down %p %p - tab_up foo %q{:a => 1 + 1}>= "Foo" bar - tab_down %p %p - tab_up foo %q> = "Foo\nBar" bar - tab_down %p %p - tab_up foo %q{:a => 1 + 1}> = "Foo\nBar" bar - tab_down %p %p - tab_up foo %q>= "Foo\nBar" bar - tab_down %p %p - tab_up foo %q{:a => 1 + 1}>= "Foo\nBar" bar - tab_down %p %p %q> %p %p %q>/ %p %p %q{:a => 1 + 1}> %p %p %q{:a => 1 + 1}>/ haml-5.1.2/test/templates/original_engine.haml000066400000000000000000000007141352226600500214140ustar00rootroot00000000000000!!! %html %head %title Stop. haml time #content %h1 This is a title! %p Lorem ipsum dolor sit amet, consectetur adipisicing elit %p{:class => 'foo'} Cigarettes! %h2 Man alive! %ul.things %li Slippers %li Shoes %li Bathrobe %li Coffee %pre This is some text that's in a pre block! Let's see what happens when it's rendered! What about now, since we're on a new line? haml-5.1.2/test/templates/partial_layout.haml000066400000000000000000000001661352226600500213150ustar00rootroot00000000000000%h1 Partial layout used with for block: = render :layout => 'layout_for_partial' do %p Some content within a layout haml-5.1.2/test/templates/partial_layout_erb.erb000066400000000000000000000002061352226600500217670ustar00rootroot00000000000000

    Partial layout used with for block:

    <%= render :layout => 'layout_for_partial' do -%> Some content within a layout <% end %> haml-5.1.2/test/templates/partials.haml000066400000000000000000000002051352226600500200750ustar00rootroot00000000000000- @foo = 'value one' %p @foo = = @foo - @foo = 'value two' %p @foo = = @foo = test_partial "partial" %p @foo = = @foo haml-5.1.2/test/templates/render_layout.haml000066400000000000000000000000511352226600500211310ustar00rootroot00000000000000= render :layout => 'layout' do During haml-5.1.2/test/templates/silent_script.haml000066400000000000000000000012661352226600500211500ustar00rootroot00000000000000%div %h1 I can count! - (1..20).each do |i| = i %h1 I know my ABCs! %ul - ('a'..'z').each do |i| %li= i %h1 I can catch errors! - begin - raise "foo" - rescue RuntimeError => e = "Oh no! \"#{e}\" happened!" %p "false" is: - if false = "true" - else = "false" - if true - 5.times do |i| - if i % 2 == 1 Odd! - else Even! - unless true Testing else indent - case 1 - when 2 Also testing else indent - else = "This can't happen!" - 13 | .foo %strong foobar - 5.times | do | |a| | %strong= a .test - "foo | bar | baz" | %p boom haml-5.1.2/test/templates/standard.haml000066400000000000000000000031741352226600500200660ustar00rootroot00000000000000!!! %html{:xmlns => "http://www.w3.org/1999/xhtml", "xml:lang" => "en-US", "lang" => "en-US"} %head %title Hampton Catlin Is Totally Awesome %meta{"http-equiv" => "Content-Type", :content => "text/html; charset=utf-8"} %body / You're In my house now! .header Yes, ladies and gentileman. He is just that egotistical. Fantastic! This should be multi-line output The question is if this would translate! Ahah! = 1 + 9 + 8 + 2 #numbers should work and this should be ignored #body= " Quotes should be loved! Just like people!" - 120.times do |number| = number Wow.| %p{:code => 1 + 2} = "Holy cow " + | "multiline " + | "tags! " + | "A pipe (|) even!" | = [1, 2, 3].collect { |n| "PipesIgnored|" }.join = [1, 2, 3].collect { |n| | n.to_s | }.join("|") | - bar = 17 %div.silent{:foo => bar} - foo = String.new - foo << "this" - foo << " shouldn't" - foo << " evaluate" = foo + " but now it should!" -# Woah crap a comment! -# That was a line that shouldn't close everything. %ul.really.cool - ('a'..'f').each do |a| %li= a #combo.of_divs_with_underscore= @should_eval = "with this text" = "foo".each_line do |line| - nil .footer %strong.shout= "This is a really long ruby quote. It should be loved and wrapped because its more than 50 characters. This value may change in the future and this test may look stupid. \nSo, I'm just making it *really* long. God, I hope this works" haml-5.1.2/test/templates/standard_ugly.haml000077700000000000000000000000001352226600500235572standard.hamlustar00rootroot00000000000000haml-5.1.2/test/templates/tag_parsing.haml000066400000000000000000000004151352226600500205570ustar00rootroot00000000000000%div.tags %foo 1 %FOO 2 %fooBAR 3 %fooBar 4 %foo_bar 5 %foo-bar 6 %foo:bar 7 %foo.bar 8 %fooBAr_baz:boom_bar 9 %foo13 10 %foo2u 11 %div.classes %p.foo.bar#baz#boom .fooBar a .foo-bar b .foo_bar c .FOOBAR d .foo16 e .123 f .foo2u g haml-5.1.2/test/templates/very_basic.haml000066400000000000000000000000321352226600500204020ustar00rootroot00000000000000!!! %html %head %body haml-5.1.2/test/templates/whitespace_handling.haml000066400000000000000000000064571352226600500222750ustar00rootroot00000000000000#whitespace_test = test_partial "text_area", :value => "Oneline" = test_partial "text_area", :value => "Two\nlines" ~ test_partial "text_area", :value => "Oneline" ~ test_partial "text_area", :value => "Two\nlines" #flattened~ test_partial "text_area", :value => "Two\nlines" .hithere ~ "Foo bar" ~ "
    foo bar
    " ~ "
    foo\nbar
    " %p~ "
    foo\nbar
    " %p~ "foo\nbar" .foo ~ 13 ~ "".each_line do |l| - haml_concat l.strip #whitespace_test = test_partial "text_area", :value => "Oneline" = test_partial "text_area", :value => "Two\nlines" = find_and_preserve test_partial("text_area", :value => "Oneline") = find_and_preserve test_partial("text_area", :value => "Two\nlines") #flattened= find_and_preserve test_partial("text_area", :value => "Two\nlines") .hithere = find_and_preserve("Foo bar") = find_and_preserve("
    foo bar
    ") = find_and_preserve("
    foo\nbar
    ") %p= find_and_preserve("
    foo\nbar
    ") %p= find_and_preserve("foo\nbar") %pre :preserve ___ ,o88888 ,o8888888' ,:o:o:oooo. ,8O88Pd8888" ,.::.::o:ooooOoOoO. ,oO8O8Pd888'" ,.:.::o:ooOoOoOO8O8OOo.8OOPd8O8O" , ..:.::o:ooOoOOOO8OOOOo.FdO8O8" , ..:.::o:ooOoOO8O888O8O,COCOO" , . ..:.::o:ooOoOOOO8OOOOCOCO" . ..:.::o:ooOoOoOO8O8OCCCC"o . ..:.::o:ooooOoCoCCC"o:o . ..:.::o:o:,cooooCo"oo:o: ` . . ..:.:cocoooo"'o:o:::' .` . ..::ccccoc"'o:o:o:::' :.:. ,c:cccc"':.:.:.:.:.' ..:.:"'`::::c:"'..:.:.:.:.:.' http://www.chris.com/ASCII/ ...:.'.:.::::"' . . . . .' .. . ....:."' ` . . . '' . . . ...."' .. . ."' -hrr- . It's a planet! %strong This shouldn't be bold! %strong This should! %textarea :preserve ___ ___ ___ ___ /\__\ /\ \ /\__\ /\__\ /:/ / /::\ \ /::| | /:/ / /:/__/ /:/\:\ \ /:|:| | /:/ / /::\ \ ___ /::\~\:\ \ /:/|:|__|__ /:/ / /:/\:\ /\__\ /:/\:\ \:\__\ /:/ |::::\__\ /:/__/ \/__\:\/:/ / \/__\:\/:/ / \/__/~~/:/ / \:\ \ \::/ / \::/ / /:/ / \:\ \ /:/ / /:/ / /:/ / \:\ \ /:/ / /:/ / /:/ / \:\__\ \/__/ \/__/ \/__/ \/__/ Many thanks to http://www.network-science.de/ascii/ %strong indeed! .foo = find_and_preserve(13) %pre :preserve __ ______ __ ______ .----.| |--.|__ |.----.| |--..--------.| __ | | __|| ||__ || __|| < | || __ | |____||__|__||______||____||__|__||__|__|__||______| %pre :preserve foo bar haml-5.1.2/test/templates/with_bom.haml000066400000000000000000000000071352226600500200660ustar00rootroot00000000000000BOMGhaml-5.1.2/test/temple_line_counter_test.rb000066400000000000000000000021241352226600500210370ustar00rootroot00000000000000# frozen_string_literal: true require 'test_helper' class TempleLineCounterTest < Haml::TestCase TESTED_TEMPLES = [ [:multi, [:code, "foo"], [:static, "bar"], [:dynamic, "baz"], ], [:multi, [:code, "foo\nbar\nbaz"], [:static, "foo\nbar\nbaz"], [:dynamic, "foo\nbar\nbaz"], ], [:case, ["'a\nb', false", [:static, "hello\n"]], [:else, [:code, "raise 'error\n'"]], ], [:escape, true, [:dynamic, "foo\nbar"]], [:escape, :once, [:dynamic, "foo\nbar"]], [:escape, false, [:dynamic, "foo\nbar"]], [:escape, true, [:static, "foo\nbar"]], [:escape, :once, [:static, "foo\nbar"]], [:escape, false, [:dynamic, "foo\nbar"]], ].freeze def test_count_lines TESTED_TEMPLES.each do |temple| code = Haml::TempleEngine.chain.inject(temple) do |exp, (symbol, filter)| case symbol when :Parser, :Compiler exp else filter.call(Haml::TempleEngine).call(exp) end end assert_equal code.count("\n"), Haml::TempleLineCounter.count_lines(temple) end end end haml-5.1.2/test/test_helper.rb000066400000000000000000000045101352226600500162630ustar00rootroot00000000000000# frozen_string_literal: true begin if ENV['TRAVIS'] && RUBY_VERSION == '2.1.2' && !defined?(Rubinius) require 'coveralls' Coveralls.wear! end rescue LoadError # ignore error for other test Gemfiles end if ENV["COVERAGE"] require "simplecov" SimpleCov.start end require 'bundler' require 'minitest/autorun' require 'action_pack' require 'action_controller' require 'action_view' require 'action_view/base' require 'nokogiri' require 'rails' Bundler.require(:default) if defined?(I18n.enforce_available_locales) I18n.enforce_available_locales = true end class TestApp < Rails::Application config.eager_load = false config.root = "" end Rails.application = TestApp Rails.backtrace_cleaner.remove_silencers! ActionController::Base.logger = Logger.new(nil) require 'fileutils' $VERBOSE = true require 'haml' require 'haml/template' TestApp.initialize! Haml::Template.options[:format] = :xhtml BASE_TEST_CLASS = if defined?(Minitest::Test) Minitest::Test else MiniTest::Unit::TestCase end class Haml::TestCase < BASE_TEST_CLASS module Declarative def test(name, &block) define_method("test_ #{name}", &block) end end extend Declarative def render(text, options = {}, base = nil, &block) scope = options.delete(:scope) || Object.new locals = options.delete(:locals) || {} engine = Haml::Engine.new(text, options) return engine.to_html(base) if base engine.to_html(scope, locals, &block) end def assert_warning(message) the_real_stderr, $stderr = $stderr, StringIO.new yield if message.is_a?(Regexp) assert_match message, $stderr.string.strip else assert_equal message.strip, $stderr.string.strip end ensure $stderr = the_real_stderr end def silence_warnings(&block) Haml::Util.silence_warnings(&block) end def assert_raises_message(klass, message) yield rescue Exception => e assert_instance_of(klass, e) assert_equal(message, e.message) else flunk "Expected exception #{klass}, none raised" end def action_view_instance Class.new(ActionView::Base) do def compiled_method_container self.class end end.new(ActionView::LookupContext.new('')) end def self.error(*args) Haml::Error.message(*args) end end haml-5.1.2/test/util_test.rb000066400000000000000000000012201352226600500157540ustar00rootroot00000000000000# frozen_string_literal: true require 'test_helper' class UtilTest < Haml::TestCase include Haml::Util def test_silence_warnings old_stderr, $stderr = $stderr, StringIO.new warn "Out" assert_equal("Out\n", $stderr.string) silence_warnings {warn "In"} assert_equal("Out\n", $stderr.string) ensure $stderr = old_stderr end def test_check_encoding_does_not_destoy_the_given_string string_with_bom = File.read(File.dirname(__FILE__) + '/templates/with_bom.haml', :encoding => Encoding::UTF_8) original = string_with_bom.dup check_encoding(string_with_bom) assert_equal(original, string_with_bom) end end haml-5.1.2/yard/000077500000000000000000000000001352226600500134005ustar00rootroot00000000000000haml-5.1.2/yard/default/000077500000000000000000000000001352226600500150245ustar00rootroot00000000000000haml-5.1.2/yard/default/.gitignore000066400000000000000000000000061352226600500170100ustar00rootroot00000000000000*.css haml-5.1.2/yard/default/fulldoc/000077500000000000000000000000001352226600500164545ustar00rootroot00000000000000haml-5.1.2/yard/default/fulldoc/html/000077500000000000000000000000001352226600500174205ustar00rootroot00000000000000haml-5.1.2/yard/default/fulldoc/html/css/000077500000000000000000000000001352226600500202105ustar00rootroot00000000000000haml-5.1.2/yard/default/fulldoc/html/css/common.sass000066400000000000000000000004251352226600500223740ustar00rootroot00000000000000#filecontents *:target, dt:target + dd background-color: #ccf border: 1px solid #88b dt font-weight: bold dd margin: left: 0 bottom: 0.7em padding-left: 3em dt:target border-bottom-style: none & + dd border-top-style: none haml-5.1.2/yard/default/layout/000077500000000000000000000000001352226600500163415ustar00rootroot00000000000000haml-5.1.2/yard/default/layout/html/000077500000000000000000000000001352226600500173055ustar00rootroot00000000000000haml-5.1.2/yard/default/layout/html/footer.erb000066400000000000000000000007551352226600500213040ustar00rootroot00000000000000<%= superb :footer %> <% if ENV["ANALYTICS"] %> <% end %>