walls.corpus

By Nathan L. Walls

Articles tagged: rails

Rails 3 – Solving NoMethodError -- undefined method for Markdown

I just switched an app from Rails 3.0.0.beta4 to Rails 3.0.0 and while poking around the app, I started getting the following error:

FooController raised exception: NoMethodError -- undefined method `markdown' for …

It took a bit of hunting through the Rails project history, but I found the relevant commit. In short, text helpers for Textile and Markdown were removed from Rails 3.0.0.

What wasn’t so obvious from actionpack/CHANGELOG was why the change was made.

Thankfully, there is a gem to add the helper methods back in. Give Formatize a look. Adding it to your Gemfile should resolve any NoMethodError exceptions

Ruby on Rails phone number validation

I recently launched a Rails application that has a phone number field available to it. In the process of writing my spec tests, I allowed the phone field to be a certain number of characters and allowed it to be empty. The formatting test, however, I left pending. I searched for, but did not find a great solution past some very unreadable regular expressions.

In the course of watching a movie this evening, I had a solution. I created an array of acceptable formats, looped over the array and checked each entry against the phone number. If I had a match, the validation passes. Setting the string match to the beginning and I can allow for extensions without being too persnickety about formatting.

Here it is (via a handy gist):

def valid_phone
  return true if phone.blank?

  phone_formats = [
    /^\(\d\d\d\) \d\d\d-\d\d\d\d/,
    /^\d\d\d.\d\d\d.\d\d\d\d/,
    /^\d\d\d-\d\d\d-\d\d\d\d/
  ]

  valid = false
  phone_formats.each do |format|
    if phone.match( format )
      valid = true
    end
  end

  unless valid
    errors.add(“Phone format isn’t recognized”)
  end
end

Here are some spec test examples.

It doesn’t handle international formats, but, for right now, it fits my needs.