21 Useful Ruby (and Rails) Code Snippets
- 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'
- 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.
- 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