Helpful Helpers
NOV
30
2008
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"
Leave a comment:
Popular Posts
Search
Tags
actionmailer activerecord ajax apache apple barcamp caching capistrano centos code golf css db delete eager loading ebay email attachment erb flash ftp fun generators get haml helpers ie sucks javascript jquery lightbox lost merb net ftp paperclip passenger php plexus post presentation rails rails machine railsconf redesign rest rjs routes rss ruby ruby on rails safari script sinatra symfony text replacement tips tutorial twitter xhtml
Projects
© 2010 Travis Roberts. All rights reserved.
Shawn Veader said on December 2, 2008:
Looks like you've already added the \s trick we talked about. (http://pastie.org/329165) Also I use a SHA digest for generating passwords: (http://pastie.org/329172) This method doesn't give the mixed case like you have in your method but should be random enough for just about anything. Either works, just something to noodle on.