frmorio's blog



frmoriofrmorio
String#split and regex lookarounds
edit Posted by frmorio on Tuesday September 11, 2007 at 12:09AM

Ruby supports regular expression quite well, so it's not surprising that one can use a lookaround to match a specific position. That also works really well with String#split, so if one needs to extract the key/value out of a string such as this:

s = "TYPE=Exterior RED=119 GREEN=105 BLUE=88 TABLEREQ=PNTTBL-01 TABLE=Primary w/XL GENERICCLR=Beige GENERICCLRCODE=31"

this will do nicely:

s.split(/\s(?=[A-Z]*=)/)

Just splitting on "space" won't work because there are spaces inside the values, too ("Primary w/XML").

Simple and useful...

frmoriofrmorio
Ruby quiz du jour answer
edit Posted by frmorio on Thursday September 06, 2007 at 10:15PM

Josh got it right.

1.0/0

indeed resolves to "Infinity". Pretty cool!

-Felix

frmoriofrmorio
Ruby quiz du jour
edit Posted by frmorio on Wednesday September 05, 2007 at 07:24PM

Question:

In Ruby, what does the following represent?

-1.0/0...0

Post your guesses as comments. Answer tomorrow. (No fair using irb.)

  • Felix and Alex and Koung

frmoriofrmorio
Applying different error display styles
edit Posted by frmorio on Wednesday July 11, 2007 at 06:09PM

Rails' build-in view helpers (text_field, etc.) can automatically render errors. The default error display is easy to use and functional, but it only goes so far. Sometimes, it's necessary to display errors in different ways in different parts of your application.

Rails provides a way of changing error rendering in "ActionView::Base.field_error_proc". Unfortunately, the only way to change the error display is on a global basis, which makes the following code non-thread safe.

We wanted to apply different error styles to different views. A simple helper method, such as this one, will allow you to specify the error display you would like to use:

<code>
def with_error_proc(error_proc)
  pre = ActionView::Base.field_error_proc
  ActionView::Base.field_error_proc = error_proc
  yield
  ActionView::Base.field_error_proc = pre
end
</code>

To define different error display styles, we can use a hash that contains various error procs:

<code>
ERROR_PROCS = {}
ERROR_PROCS[:errors_below] = Proc.new do |html_tag, instance|
  html_tag+' error'
  # renders errors below the field
end
</code>

Finally, to use this in your controller, just wrap the render method with #with_error_proc. It's also possible to use this directly in your view.