Module: Hanami::View::Escape::InstanceMethods

Defined in:
gems/gems/hanami-view-1.3.3/lib/hanami/view/escape.rb

Overview

Since:

  • 0.4.0

Instance Method Summary collapse

Instance Method Details

#_escape(object) ⇒ Hanami::View::Escape::Presenter (private)

Force the output escape for the given object

Examples:

View usage

require 'hanami/view'

User = Struct.new(:first_name, :last_name)

module Users
  class Show
    include Hanami::View

    def user
      _escape locals[:user]
    end
  end
end

# ERB template:
#
# <div id="first_name">
#   <%= user.first_name %>
# </div>
# <div id="last_name">
#   <%= user.last_name %>
# </div>

first_name = "<script>alert('first_name')</script>"
last_name  = "<script>alert('last_name')</script>"

user = User.new(first_name, last_name)
html = Users::Show.render(format: :html, user: user)

html
  # =>
  # <div id="first_name">
  #   &lt;script&gt;alert(&apos;first_name&apos;)&lt;&#x2F;script&gt;
  # </div>
  # <div id="last_name">
  #   &lt;script&gt;alert(&apos;last_name&apos;)&lt;&#x2F;script&gt;
  # </div>

Parameters:

  • object (Object)

    the input object

Returns:

  • (Hanami::View::Escape::Presenter)

    a presenter with output autoescape

See Also:

Since:

  • 0.4.0

def _escape(object)
  ::Hanami::View::Escape::Presenter.new(object)
end

#_raw(string) ⇒ Hanami::Utils::Escape::SafeString (private)

Mark the given string as safe to render.

!!! ATTENTION !!! This may open your application to XSS attacks.

Examples:

View usage

require 'hanami/view'

User = Struct.new(:name)

module Users
  class Show
    include Hanami::View

    def user_name
      _raw user.name
    end
  end
end

# ERB template
# <div id="user_name"><%= user_name %></div>

user = User.new("<script>alert('xss')</script>")
html = Users::Show.render(format: :html, user: user)

html # => <div id="user_name"><script>alert('xss')</script></div>

Presenter usage

require 'hanami/view'

User = Struct.new(:name)

class UserPresenter
  include Hanami::Presenter

  def name
    _raw @object.name
  end
end

user      = User.new("<script>alert('xss')</script>")
presenter = UserPresenter.new(user)

presenter.name # => "<script>alert('xss')</script>"

Parameters:

  • string (String)

    the input string

Returns:

  • (Hanami::Utils::Escape::SafeString)

    the string marked as safe

Since:

  • 0.4.0

def _raw(string)
  ::Hanami::Utils::Escape::SafeString.new(string)
end