Skip HTML output in special label_tag helper in Rail 3

I have this class class ErrorFormBuilder, which allows me to add a description of the error next to the corresponding field in the form of a form:

    class ErrorFormBuilder < ActionView::Helpers::FormBuilder
  #Adds error message directly inline to a form label
  #Accepts all the options normall passed to form.label as well as:
  #  :hide_errors - true if you don't want errors displayed on this label
  #  :additional_text - Will add additional text after the error message or after the label if no errors
  def label(method, text = nil, options = {})
    #Check to see if text for this label has been supplied and humanize the field name if not.
    text = text || method.to_s.humanize
    #Get a reference to the model object
    object = @template.instance_variable_get("@#{@object_name}")

    #Make sure we have an object and we're not told to hide errors for this label
    unless object.nil? || options[:hide_errors]
      #Check if there are any errors for this field in the model
      errors = object.errors.on(method.to_sym)
      if errors
        #Generate the label using the text as well as the error message wrapped in a span with error class
        text += " <br/><span class=\"error\">#{errors.is_a?(Array) ? errors.first : errors}</span>"
      end
    end
    #Add any additional text that might be needed on the label
    text += " #{options[:additional_text]}" if options[:additional_text]
    #Finally hand off to super to deal with the display of the label
    super(method, text, options)
  end
end

But HTML:

text += " <br/><span class=\"error\">#{errors.is_a?(Array) ? errors.first : errors}</span>"

escaped by default in the view ... I tried adding the parameter {: escape => false}:

super(method, text, options.merge({:escape => false}))

without success

Is there any way around this behavior?

thank

+3
source share
2 answers

Have you tried making your html_safe string?

irb(main):010:0> a = "A string"
=> "A string"
irb(main):011:0> a.html_safe?
=> false
irb(main):012:0> b = a.html_safe
=> "A string"
irb(main):013:0> b.html_safe?
=> true

See http://www.railsdispatch.com/posts/security and scroll down to β€œWhat you need to know” below:

, Rails , . Rails , . , - .

Rails , , . , .

, , .

+9

<%= raw your_variable_here %>

+8

Source: https://habr.com/ru/post/1747417/


All Articles