Helpful Helpers
Nov 30, 2008 - Comments
Here is a list of helper methods that we use a lot at Plexus to make our jobs easier. A few have been referenced in previous posts, but I thought I'd list them all here in one place.
Strip text for pretty URLs
You can use this method to replace all non-alphanumeric characters to dashes in a title or name when you're including them in the URL.
This is the route I use for my posts on this blog:
m.post_details ':year/:month/:day/:title', :action => "by_date",
:requirements => { :year => /(19|20)\d\d/, :month => /[01]?\d/, :day => /[0-3]?\d/},
:day => nil, :month => nil, :title => nil
And here is the helper to strip out characters in the title when creating the URL:
# Replace all non-alphanumeric characters with dashes def strip_chars(string='') string.gsub(/\s+/,'-').gsub(/[^a-z0-9\-]+/i, '') end
You can call the helper when you generate the route.
post_details_path(:year => @post.date.year, :month => @post.date.month, :day => @post.date.day, :title => strip_chars(@post.title))
Generate a random password of n length
I've actually got a whole other post for just this helper, but decided to include it in this list.
def generate_password(length=6)
chars = 'abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ23456789'
password = ''
length.times { |i| password << chars[rand(chars.length)] }
password
end
It will generate a 6 digit password by default, but you can specify the desired length.
generate_password => "Q6Kfze" generate_password(10) => "ZSJcmtRH5q"
Built-in rails helpers
These following helpers are built into rails, but you may not know about them.
["this", "that", "the other"].to_sentence => "this, that, and the other"
number_to_currency(123456789) => "$123,456,789.00" number_to_human_size(123456789) => "117.7 MB" number_to_phone(1234567890, :area_code => true) => "(123) 456-7890"
There are a ton of string inflector helpers
"under_scored".dasherize => "under-scored" "names_and_titles".humanize => "Names and titles" "lower case title".titleize => "Lower Case Title"

