October 2011
2 posts
9 tags
Decorating Models from the View Layer with Draper
Draper is a great gem allowing for the Decorator pattern to easily be applied to ActiveRecord models. When integrating Draper into an existing application, a decorator or collection of decorators must be retrieved/built instead of ActiveRecord models in order to use the functionality of your decorators (the decorators include all functionality of the ActiveRecord model they’re decorating)....
Oct 12th
12 notes
7 tags
Dynamically Building Squeel DSL Blocks
Given a partial query such as Jas D I recently needed to search for matches in a users table across multiple fields: Email (:email) Username (:username) First Name (:first_name) Last Name (:last_name) I also wanted this same search to be reusable; flexible enough to let me specify other columns within the User model to search by, such as just the first_name and last_name fields. The...
Oct 7th
August 2011
4 posts
8 tags
Ruby Capitalization Obeying English Title Grammar
Strings passed will be formatted to obey English title rules. "HAPPY BIRTHDAY".proper_titleize #=> Happy Birthday "OvEr THE MouNTaiN And ThrOuGH thE WooDS".proper_titleize #=> Over the Mountain and Through the Woods A link to the gist can be found below the source. class String # Converts a string into a properly capitalized English title # # @param [String] string the string to...
Aug 23rd
128 notes
8 tags
Spelling Suggestions from Google in Ruby
Google used to offer a SOAP API for spelling suggestion/correction but put it out of service in November 2010. Since then the only way I had found to reliably get Google’s recommended spelling suggestion for an incorrectly spelled phrase was through the same interface their toolbar browser extension uses to help correct spelling mistakes. My SpellCheck project is a PHP5 tool that asks Google...
Aug 9th
4 notes
5 tags
Validating YAML-style Tag Strings with Javascript
This has an admittedly very specific use-case, but recently I needed to validate strings matching the following formats: [apples, oranges] [[apples, oranges]] [apples, oranges, [peaches, grapes]] The bracket nesting is important as it will later be parsed by a YAML parser to generate nested arrays of strings [ "apples", "oranges", [ "peaches", "grapes" ] ] and then...
Aug 5th
24 notes
3 tags
MooTools focusedKeyUp Event
Recently needed to apply a keyup event to a series of textfields during MooTools domready event, but only have each field’s event execute when that field has the user’s focus. /** * Custom MooTools event, restricting firing of the keyUp event to only when the target element has focus. * * Usage: * some_element.addEvent('focusedKeyUp', function(event) { * console.debug('A...
Aug 5th
9 notes
May 2011
1 post
8 tags
Using intern to Reference Routes Dynamically
In config/routes.rb if routes such as the following exist: match "users/customers" => "users#customers", :as => :users_customers, :via => :get match "users/employees" => "users#employees", :as => :users_employees, :via => :get match "users/:id/toggle-status" => "users#toggle_status", :as => :users_toggle_status, :via => :put the views associated with the...
May 20th
11 notes
April 2011
2 posts
7 tags
Reverse Pagination Count with Kaminari
When displaying a threaded conversation with messages paginated by Kaminari, I had the unique requirement to display messages in DESC order by their creation date. This meant that if there were 12 messages with 5 per page, the breakdown would be Page 1: messages 12 - 8 Page 2: messages 7 - 3 Page 3: messages 2 - 1 To actually display the message number next to each message, it had to be...
Apr 26th
3 notes
9 tags
Parsing and Pluralizing Model Names in Rails
Recently working with Kaminari, I wanted to have text display next to the pagination links like 283 Items - Page 3/15 I wanted the Items text to be dynamic according to the model the paginated collection was representing. Looking over my model names I found converting each to a human readable version would work great in all cases I needed a paginator. Simply using pluralize (I use singular...
Apr 25th
4 notes
August 2010
3 posts
10 tags
Amazon S3 + Nightly Database Backups
Amazon S3 is a cost-effective, redundant, and straight-forward solution for off-site data backups. Using the highly recommended aws command line tool by Tim Kay and a simple shell script running nightly, creating an automatic remote database backup is easy. After installing aws, I created a shell script as shown below. #!/bin/bash export AWS_ACCESS_KEY_ID= # your aws access key id export...
Aug 25th
5 tags
Testing for Input Focus
Though part of the HTML5 Specification, the activeElement attribute is now supported by all major browsers and offers the ability to determine whether an element currently has the user’s focus very easily. Previously making the determination for which input element currently had focus was done using multiple event handlers applied to all input elements. (Note: The selector below does not...
Aug 22nd
7 tags
Caching Static Assets with Cache-Busting Support...
(Note: This technique can be applied anywhere. This article is specifically related to a Symfony 1.4 implementation) As recommended in the Google Page Speed best practices, static resources should be cached locally in the browser. This means setting a far-future expiration date on filetypes such as .css and .js content. This first step is achieved rather simply by adding something like below to...
Aug 18th
July 2010
1 post
8 tags
Symfony Functional Tests + PHP APC Cache Slam...
After implementing query caching using Doctrine’s Doctrine_Cache_Apc interface in a Symfony application I am working on, when running the application’s functional tests, warnings were returned intermittently in a few places $ [apc-warning] Potential cache slam averted for key ... In APC >= 3.0, an apc.slam_defense configuration option was added in attempt to avoid repeated...
Jul 9th
2 notes
June 2010
4 posts
6 tags
Symfony + sfController::getPresentationFor() +...
There may be times when part or all of a text/plaintext version of an action’s template needs to be rendered for use from within another action who’s display format is set as text/html. For example, if there is a text/plaintext version of an order receipt that appears within an application, and that same version of the order receipt needs to be mailed to a user from within a separate...
Jun 16th
9 tags
Doctrine 1.2 + Sluggable Template + Conditionally...
Doctrine provides a stock Sluggable template behavior that can be applied to models, generating a slug based on one or more columns for a Doctrine_Record instance. In most cases it is best practice not to modify a slug after it is generated, since one or more external sources may be referencing a URL to the Doctrine_Record instance by the original slug. If the slug is modified, those URLs...
Jun 14th
5 tags
PayPal Sandbox + Website Payments Pro Integration
Setting up a new Website Payments Pro account for integration with an application I’m working on, it required a sandbox account be setup through http://developer.paypal.com/. Though the Test Accounts page is very simple to work with, it was a little tricky sorting out exactly how to integrate a Website Payments Pro account with a business test account that will actually process payments...
Jun 10th
1 note
6 tags
Symfony's format_date(), l10n Support, and Custom...
Symfony comes with some great i18n and l10n support. The DateHelper comes with functionality for templates to provide locale-specific date formats. There are a bunch of default formats that can be easily used as format_date(strtotime('now'), 'P', 'en_US'); // Outputs 'Monday 7 June 2010' format_date(strtotime('now'), 'P', 'fr_FR'); // Outputs 'Lundi 7 Juin 2010' Some of the pre-defined...
Jun 7th
1 note
May 2010
3 posts
9 tags
Subversion: Merging from trunk to branch; Back to...
During a normal development cycle, multiple branches of trunk may exist simultaneously with different features/fixes being developed within each. In order to keep trunk relatively stable at all times, it is a good idea to merge any changes to trunk since the branch was created into that branch when the branch is ready to be pushed into trunk. Confusing? The process is as follows Create a branch ...
May 13th
8 tags
Introducing SpellCheck
After learning Github is now offering SVN support (nearly all of my development work is done using SVN), I decided it was time to properly version my small changes to the great gRaphael library by forking the original code with my own account. I also decided to start to maintain smaller utilities I write for personal use through git on Github as well. The first of these packages is...
May 9th
6 tags
Shifting the Window to Display Anchors Below Fixed...
When browsing to an anchor within an page, all browsers (that I know of) scroll the page to the anchored element such that the element is at the very top of the visible browser window. This is a problem when a site design includes a fixed element at the top of the browser window. A little bit of Javascript (via MooTools) can fix this: var AnchorFix = new Class({ Implements: Options, ...
May 5th
April 2010
1 post
3 tags
MooTools' .attempt(), arguments, and Javascript's...
arguments is a local object variable available within any function in JavaScript. Arguments can be accessed as shown in foo() below. function foo(){ console.debug(arguments); // ['a', 'b'] console.debug(arguments[0]); // 'a' } foo('a', 'b'); This is convenient for functions that may need to accept an arbitrary number of parameters. But if these arguments need to again be passed on to...
Apr 30th
March 2010
4 posts
4 tags
MooTools toElement() - Using a Class Instance to...
In MooTools the $() is used in part to ensure the element passed to $() is extended by MooTools. Clientcide points out a great tip with the native Class toElement() function. Aside from the benefits from the use of this from outside of a class passing an instance variable to $(), I like to use toElement() in combination with $(this) from within my Class objects simply for brevity. var someClass...
Mar 24th
6 tags
Opening Folder from Terminal in Gnome
The majority of the file management I do at work is through the terminal, however sometimes it is necessary to view/work with files through Nautilus. I’ve added the following command to my ~/.bashrc, causing openme to launch the current working directory in Nautilus. alias openme='nautilus --browser . 2> /dev/null'
Mar 19th
4 tags
Markdown and Doctrine_Record - Re-Parsing Data...
To prevent user-generated content formatted with Markdown from being re-parsed by the Markdown parser every time it is called to be rendered as HTML, it is best practice to store the parsed/converted HTML version of the original Markdown text alongside the original Markdown markup. The parsing of this user-generated content can only be done as necessary using Doctrine’s preSave event...
Mar 11th
6 tags
Symfony 1.4 + Doctrine 1.2 - Transactions
Hoping there is a simpler way that I am missing, here is how to begin a new transaction with Doctrine 1.2 through Symfony 1.4. It was the call to sfDoctrineDatabase::getDoctrineConnection() which I had to lookup in the docs1. $connection = sfContext::getInstance()->getDatabaseManager()->getDatabase('default')->getDoctrineConnection(); $connection->beginTransaction(); try { //...
Mar 3rd
1 note
February 2010
2 posts
5 tags
Parsing Email Addresses From a Log File
Recently I needed to parse all unique email addresses from a very large plaintext log file. A simple grep would not suffice because there were many cases where multiple email addresses appeared on the same line. Realizing there are many solutions to this problem, here is the one I came across1 which I found most suitable for my needs. perl -wne'while(/[\w\.\-]+@[\w\.\-]+\w+/g){print...
Feb 26th
2 notes
3 tags
Doctrine_Record: Ignoring Custom Finders
Some Conversation model might have a many-to-many relationship between itself and some Participant model through some ConversationsParticipants model. By default in Doctrine, to get all Participants for some Conversation, the magic finder for $participants = Conversation->Participants; would return Participant instances in the order they were created (ordered by the primary key). When a...
Feb 26th
November 2009
1 post
7 tags
sfLoader::loadHelpers is now Deprecated (Symfony...
As of Symfony 1.3, the loadHelpers() method in the sfLoader class is deprecated. The sfLoader::loadHelpers() method is deprecated. Please use the same method from sfApplicationConfiguration. Though it only took 3 minutes to find the proper way to call the sfApplicationConfiguration instance, I thought I’d post it here for...
Nov 15th
September 2009
1 post
15 tags
Transferring a Live Site to a New Server Using...
Using cPanel/WHM it is very easy to transfer an existing cPanel account between servers. Coordinating this with a client who manages DNS on their own can make things a bit tricky, especially when their MX records point to the same server for webmail service. In order to guarantee no downtime on the site, typically I copy a cPanel account over to the new server including all site files and email...
Sep 3rd
August 2009
1 post
8 tags
Fixing 'Unsupported Protocal' Errors When...
Soon after updating to PHP5.3 on my local computer I found that some legacy code I maintain which can not be updated currently no longer worked. After a bit of research1, I found the best solution for now was for me to downgrade back to the latest stable version of PHP 5.2, PHP 5.2.10. I needed to reinstall a few PEAR and PECL extensions which much of the code I maintain depends on. [~] $ sudo...
Aug 23rd
May 2009
3 posts
4 tags
Bash Shortcuts Using the Exclamation Point
The shell provides multiple shortcuts via the usage of the exclamation point when trying to execute recently performed commands. Err the Blog’s Bash Cheat Sheet provides the following tips and more. If you need to run the most recently executed command again !! If the last command run requires super user privileges sudo !! Run the most recently executed command beginning with...
May 29th
1 note
3 tags
Making PROMPT_COMMAND More Informative
On Mac/Linux the shell’s command prompt is typically fairly uninformative, displaying only the top level of the current working directory path. If you are currently at /home/me/sites/mysite, the prompt might look something like [mysite]$ ... This isn’t as useful as it could be. LinDesk details multiple ways to make the command prompt more informative. Based on the information there...
May 26th
7 tags
MooTools SuperSleight Implementation for IE .png...
Recently I had to slice converted a site mockup to XHMTL and CSS. Part of the implementation required that the width of the site be what I like to call “static-variable width”. The width of the site is not dependent on the width of the browser as a fluid layout is, but a slider control is available to the user to grow or shrink the width of the site as they desire. Due to the...
May 25th
April 2009
2 posts
9 tags
Fixing Crontab Permissions for Jailshell cPanel...
Using CentOS 5 on my VPS, I recently found that newly created cPanel accounts running cPanel/WHM 11.24 RELEASE seemed to have some trouble properly setting permissions to allow the jailshell cPanel users to access/manage their crontab. Setting up cron jobs via cPanel’s web interface itself worked just fine, but when trying to manage a jailshell users crontab via shell, the permissions were...
Apr 12th
7 tags
Aiding the SVN Commit Process
The source code for D4core is maintained in and SVN repository. I have found it helpful to create a .cleanup and .commit Bash script in the root directory of our framework’s repository. .cleanup has the task of removing cached files, temporary files, and log files which are no longer relevant to the current development cycle. It also use it currently to reformat our XML configuration file...
Apr 3rd
March 2009
5 posts
5 tags
sed one-liners reference page →
An incredibly useful quick-reference for one-line sed1 commands. man page for sed ↩
Mar 30th
8 tags
Dumping the Number of Open Connection to Port 80...
This displays the number of open connections to port 80 on a server, dumping the ip address/connection count pairs in ascending order. netstat -anlp | grep :80 | awk '{print $5}' | awk -F: '{print $1}' | sort | uniq -c | sort -n This can be useful in combination with grep1 searches performed on httpd fullstatus to determine if a DOS attack is being performed on a server. man page for...
Mar 30th
7 tags
Trac - SubversionException: Can't set position...
When recompiling SVN 1.5.5 from source, making sure to include the swig-py bindings to allow Trac to read from local SVN repositories, I used the following ./configure command ./configure --prefix=/usr/local/svn-1.5.5/ --with-apr=/usr/local/apr/bin --with-apr-util=/usr/local/apr/bin --with-neon=/usr/bin --with-apxs=/usr/local/apache/bin/apxs When trying to view my repository I was presented...
Mar 26th
8 tags
Clear Hanging Apache Semaphores
Restarting httpd while trying to alleviate high load on one of the servers I manage, I was recently presented with the following error (28)No space left on device: Couldn't create accept lock After some research I found running the following command1 ipcs -s showed there were a bunch of semaphores hanging around even though apache had been stopped normally via service httpd restart ...
Mar 25th
1 note
6 tags
Clear /.svn Directories From a Working Copy
Below is one way to quickly and simply clear all /.svn directories from a SVN working copy; useful in a variety of situations. find . -type d -name .svn -exec rm -rf '{}' ; -print 2> /dev/null
Mar 25th
February 2009
1 post
13 tags
Making AppleTV Encoded Video Files PlayStation 3...
Using Handbrake to rip DVDs, I use a slight customization of the default AppleTV encoding settings. I find the quality-to-filesize ratio is great for nearly zero setup time. But when trying to play the encoded .mp4 video files on my PlayStation 3, the video format was unrecognized. Running this1 over a movie.mp4 AppleTV encoded movie fixes this issue, while still maintaining compatibility with...
Feb 25th