Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-6 of 6 total  RSS 

Parsing Errors on Command Line

Get PHP parsing errors on command line. Useful for those extreme cases where you can't get them to print to the browser.

find . -name \*.php \! -exec php -l {} \;

Testing for Exception message in Rails

e = assert_raise(RuntimeError) { my_code_that_raises }
assert_match(/Error message here/i, e.message)..

Putting the errors in the right place

The idea is to display the error near the field instead of in global area at the top of the page.
Simple… first go into your view and delete the
error_messages_forobject’


Then stick this in your application helper.


# application_helper.rb
def error_for(object, method = nil, options={})
if method
err = instance_variable_get("@#{object}").errors.on(method).to_sentence rescue instance_variable_get("@#{object}").errors.on(method)
else
err = @errors["#{object}"] rescue nil
end
options.merge!(:class=>’fieldWithErrors’,
:id=>"#{[object,method].compact.join(’_')}-error",
:style=>(err ? #{options[:style]}":"#{options[:style]};display: none;")
)
content_tag("p",err || "", options )
end


Then in your form view, add an ‘error_for’ call wherever you need one…

# _form.rhtml
  <p><label for="code_project_name">Name</label>
  <%= text_field ‘code_project’, ‘name’  %>
  <%= error_for ‘code_project’, ‘name’ %></p>


If the model fails a validation test, then it will show the message right next to the field that caused the validation problem.
Also note that if you define an instance variable called @errors containing a hash of field_names and messages, they will also be used. This is handy for those form fields that don’t correspond to a model attribute.

Helper to display Rails flashes

If you use the convention of using :notice, :warning and :error with your flashes, then this simple helper will allow you to display your flashes easily, and it supports the storage of ActiveRecord::Errors in flash[:error] as well.

  def display_standard_flashes(message = 'There were some problems with your submission:')
    if flash[:notice]
      flash_to_display, level = flash[:notice], 'notice'
    elsif flash[:warning]
      flash_to_display, level = flash[:warning], 'warning'
    elsif flash[:error]
      level = 'error'
      if flash[:error].instance_of? ActiveRecord::Errors
        flash_to_display = message
        flash_to_display << activerecord_error_list(flash[:error])
      else
        flash_to_display = flash[:error]
      end
    else
      return
    end
    content_tag 'div', flash_to_display, :class => "flash #{level}"
  end

  def activerecord_error_list(errors)
    error_list = '<ul class="error_list">'
    error_list << errors.collect do |e, m|
      "<li>#{e.humanize unless e == "base"} #{m}</li>"
    end.to_s << '</ul>'
    error_list
  end

ActiveRecord::Errors#to_xml

Here’s a method that will allow you to call to_xml on an ActiveRecord::Errors object. We’re using this to pass errors between web apps via a web service api.

class ActiveRecord::Errors
  def to_xml(options = {})
    options[:indent] ||= 2
    options.reverse_merge!({ :builder =>
      Builder::XmlMarkup.new(:indent =>
        options[:indent]), :root => "errors" })
    options[:builder].instruct! unless options.delete(:skip_instruct)

    options[:builder].__send__(options[:root].to_s.dasherize) do |xml|
      @errors.each do |key, value|
        xml.__send__(key.to_s.dasherize) do |xm|
          for message in value
            xm.message(message)
          end
        end
      end
    end

  end
end

Use background color to show error fields instead of wrapping them in a div

Using the default rails field_error_proc may lead to some layout headaches--your form looks perfect until, uh-oh, someone entered an invalid email address and Rails adds a fieldWithError-styled div that wraps around the problem field.

While this works in many cases, some pixel-perfect layouts may not be able to tolerate the 2-pixel padding around the text_field caused by the red border. An alternative is to change the background color of the offending field.

Include the following code in environment.rb (or use a "require" like I do):

ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|
  error_style = "background-color: #ffff80"
  if html_tag =~ /<(input|textarea|select)[^>]+style=/
    style_attribute = html_tag =~ /style=['"]/
    html_tag.insert(style_attribute + 7, "#{error_style}; ")
  elsif html_tag =~ /<(input|textarea|select)/
    first_whitespace = html_tag =~ /\s/
    html_tag[first_whitespace] = " style='#{error_style}' "
  end
  html_tag
end


See my blog.inquirylabs.com for more Rails stuff.
« Newer Snippets
Older Snippets »
Showing 1-6 of 6 total  RSS