21 Useful Ruby (and Rails) Code Snippets
Basic Ruby
- Detect if you're running on Windows - Adds a method to Kernel called is_windows?
- Random Alphanumeric String Generator - Produces a random string of a chosen length using A-Za-z0-9.
- Full intersection between 2 arrays - Like '&' but doesn't remove duplicates in the original array.
- Call .sort with a block - Basic Ruby, but contains an extended section with an optimization and a to_proc version.
- Date.distance_to method - Gives you the distance between two dates in years, months, and days
- Match identical strings on the same line - Clever regex
- Quickly match first instance of a regex match
- Return 'x' random elements from an array - Extends the Array class with 'randomly_pick'
Advanced Ruby
- Non-persistent ActiveRecord - Lets you create AR models without a corresponding database table
- Ruby Object Creation Tracer - Tells you where your objects are being created in your program
- Basic OpenGL Ruby example - An interesting place to start if you want to get into graphics / OpenGL.
- BlankSlate: Clean a class down to its barest minimum methods - Self explanatory!
- Temporarily overriding class methods to create mock methods
- Cheap rsync replacement - Interesting way of writing a rsync-like file transfer program
- 6 line P2P client - In response to the well-known Python one..
- Parsing UTF encoded strings - Doesn't require jcode.
Rails
- Force output to download as a file in Rails - For situations when you want a results file to be saved by the user, rather than shown in the browser.
- Highlight link for current action in Rails - A basic helper that highlights any links to the current action
- Easy Selects in Rails - Adds methods to ActiveRecord to return arrays suitable for select boxes.
- Time warp for functional and unit testing - Ideal for testing 'only allow X requests in Y hours', etc.
- Create a 'countries' table (with data) for your Rails app
June 2, 2006 at 2:40 pm
Holy cow, Peter! This site is great. Especially lists like this one. Thanks for taking the time to do this. It's a very useful resource.
June 2, 2006 at 3:47 pm
Thanks for the encouragement, Tom, it's much appreciated :)
Bit of a cheeky comment, but if you could del.icio.us the site, that'd also be much appreciated ;-)
June 2, 2006 at 5:08 pm
Done. Can't believe I hadn't already!
This site has replaced about 10 feeds in my reader.
June 2, 2006 at 9:19 pm
Haha, that's okay, much appreciated! :)
I'll try to make sure it doesn't disappoint. Hopefully those 10 feeds are ones I've been reading ;-)