Category Archives: Development

Making sense of the difference between AMD, CommonJS, RequireJS and Browserify

A colleague starting on javascript frameworks asked me what’s the difference between AMD, CommonJS, RequireJS and Browserify. He was under the impression they are 4 separate technologies so here’s a quick overview for those who might be confused. Take note this article is not meant as an in-depth discussion but more of an overview for people unfamiliar with the terms and not sure where to begin.

For a start, we need to understand they are not from the same category. Asynchronous module definition (AMD) and CommonJS are styles/specifications of writing modular code in javascript, while RequireJS and Browserify are 2 popular implementation/helper for them respectively. RequireJS allows you to work with modules the AMD way in the browser, and Browserify for the CommonJS way.

AMD

Asynchronous module definition is designed for the browser from the start. It allows your frontend application to load the starting point of your app, which in turn loads it’s dependencies on the fly. When using the requireJS implementation, it’s syntax looks like: Continue reading

Ryan’s Drupal 7 troubleshooting checklist

New to Drupal or a little rusty? This checklist is to help speed up your troubleshooting process. The list is currently at version 0 and I hope to improve it by giving more structure along with associating/clustering each item with symptoms. Let me know if you want to help! Continue reading

Triggering default Ajax behaviour in Drupal textfields for better UX

By default, the addressfield form elements triggers Ajax requests on change, which means textfields only triggers when blurred. This may leave the user wondering what to do if the next field depends on the results of the Ajax request. To trigger the default Ajax behaviour on other events, you can do


$('body').on('change keyup paste', '.selector.for.your.element', function(e) {
var current_value = $(this).val();
// Do some checks before the request.
if (current_value.length === 4){
// Blur the textfield.
$(this).trigger("blur");
return false;
}
});

A few notes:
on() is used so that the event is live. i.e. still bound after the element is updated, which is common in Ajax forms. If event listeners are added to the element directly, it is lost after the form is updated.

The events ‘change’, ‘keyup’, ‘paste’ is used to capture common events where the contents of the field might change.

Adding even and odd classes to checkboxes in Drupal 7

While theming a page for a client, I came across an interesting challenge: adding even and odd classes to checkboxes. Normally I would have gone with javascript or CSS3 (:nth-child), but I wondered if it can be achieved in ‘the Drupal way’ and achieve the best cross browser support. Google didn’t turn up any results so I decided to do a quick exercise on form element theming. Here’s how I got it to work.

Add our own checkboxes processor. See hook_element_info_alter.

function MYTEMPLATE_element_info_alter(&$type){
  // Append our processor
  $type['checkboxes']['#process'][] = 'MYTEMPLATE_process_checkboxes';
}

Implement the customer checkboxes processor to add the classes we want. See form_process_checkboxes

function MYTEMPLATE_process_checkboxes($element){
  // Loop through options to add striping class and attribute
  if (count($element['#options']) > 0) {
    $i = 0;
    foreach ($element['#options'] as $key => $choice) {
      $element[$key]['#attributes']['class'][] = ($i % 2 == 0) ? 'odd' : 'even';
      $i++;
    }
  }
  return $element;
}

I quickly realized that while this added the even and odd classes on the <input> elements, it would be easier for the themer to have it on the form element wrapper as well. So I decided to add a ‘striping’ key to ‘#attributes’ so that I can identify it in the form element wrapper.

The new processor:

function MYTEMPLATE_process_checkboxes($element){
  // Loop through options to add striping class and attribute
  if (count($element['#options']) > 0) {
    $i = 0;
    foreach ($element['#options'] as $key => $choice) {
      $element[$key]['#attributes']['class'][] = ($i % 2 == 0) ? 'odd' : 'even';
      $element[$key]['#attributes']['striping'] = ($i % 2 == 0) ? 'odd' : 'even';
      $i++;
    }
  }
  return $element;
}

Next, modify the template_form_element() to add the classes on the form element wrapper.

function MYTEMPLATE_form_element($variables) {
  ...
  if (!empty($element['#attributes']['striping'])) {
    $attributes['class'][] = $element['#attributes']['striping'];
  }
  $output = '<div' . drupal_attributes($attributes) . '>' . "\n";
  ...
}

Clear the class registry and we are done. This is by no means the best method available, but is definitely the most straightforward way that jumped at me. If you have a more efficient way do share in the comments.

Building with old iPhone SDKs with new XCode versions

If you have recently updated to the latest version of XCode you might be wondering how to get your 6.1 iPhone SDK back. The new XCode versions do not come with previous iPhone SDK’s so we need to obtain them from older XCode (download them from Apple) and symbolic link them to the right place. First, copy the SDK’s from the download and place them somewhere which wouldn’t get replaced on future XCode upgrades. For my case I left them in /SDKs/iPhoneOS.platform/Developer/SDKs. Next, show package contents of your current XCode.app and navigate to Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs, and make the link with this:

sudo ln -s /SDKs/iPhoneOS.platform/Developer/SDKs/iPhoneOS6.1.sdk iPhoneOS6.1.sdk

Just remember to redo the links whenever you update XCodes.

Exporting your developer and distribution certs and keys from PC to Mac

Migrating my iOS developer and distribution identities from PC to Mac turn out to be a little more involved than expected. I assumed I can import the .cer and .key into my keychain and be done with it, but my Mac does not seem to recognise .cer files at all. So if you’re figuring out how to get the .cer and .key pair to install on your Mac, here’s how.

Before you begin
Have your certificate, key, and Apple’s World Wide Developer Relations (WWDR) certificate ready (available here). Mine’s named ‘developer_identity.cer’, ‘developer_identity.key’ and ‘AppleWWDRCA.cer’, so remember to replace with your own naming when running the following commands.

Open terminal and cd into the directory where the files are residing, then run these commands:

[sourcecode language=”plain”]openssl x509 -inform der -in developer_identity.cer -out developer_identity.pem

openssl x509 -inform der -in AppleWWDRCA.cer -out AppleWWDRCA.pem

openssl pkcs12 -export -out cert.p12 -inkey developer_identity.key -in developer_identity.pem -certfile AppleWWDRCA.pem
[/sourcecode]

What’s the AppleWWDRCA.cer for?
It’s Apple’s World Wide Developer Relations (WWDR) certificate required to certify your builds. Think of it as Apple’s signature on a “the internet trusts this application because Apple trusts it” agreement. You had your signature from the developer_identity obtained from Apple, and now you have Apple’s signature.

AFNetworking failing with “Garbage at end” when using php’s cURL

If you don’t set CURLOPT_RETURNTRANSFER to true, cURL outputs the results of the CURL operation directly into the response, which is then sent back to AFNetworking. If the cURL operation outputs anything but valid JSON, this most likely will cause the JSON decoding to fail with:

[sourcecode language=”plain”]Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (Garbage at end.) UserInfo=0x753e5c0 {NSDebugDescription=Garbage at end.}[/sourcecode]

To turn on CURLOPT_RETURNTRANSFER, do:
[sourcecode language=”plain”]curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);[/sourcecode]

Hope this helps prevent some hair-pulling during midnight debugs.

Parse with deprecated Facebook headers on iOS gives “Semantic Issue” errors

If your app uses the deprecated Facebook headers, i.e. #import "Facebook.h" instead of #import <FacebookSDK/FacebookSDK.h>, importing Parse.h using the standard instructions at https://www.parse.com/apps/quickstart_push would fail your build with multiple errors of

Semantic Issue, Redefinition of enumerator 'FBSessionsStateCreated', 'FBSessionState....', etc.

The issue is that Parse imports the Facebook headers internally. To work around this, open Parse.h and replace

#if __has_include(<FacebookSDK/FacebookSDK.h>)
#import <FacebookSDK/FacebookSDK.h>

with

#if __has_include("Facebook.h")
#import "Facebook.h"

Next, open PFFacebookUtils.h and replace #import <FacebookSDK/FBSession.h> with #import "FBSession.h" and you’re good to go.

Beta Testing for Leendy

After 3 months of weekend development sessions, I’m excited to finally start the beta testing phase for Leendy. I’ve even squeeze out time to do up the website and Facebook page!

Leendy is the easiest way to share and swap things among friends while saving the earth. It is based on the collaborative consumption philosophy of sharing to cut down on resource wastage and allow everyone to enjoy more value out of existing items. If you have an iPhone and some free time, why not register as a tester?

Running manage.py locally with auto pythonpath

While trying to run my manage.py locally to syncdb, it complains that my project’s .settings isn’t in the sys.path. Instead of setting it manually, I decided to add it into the manage.py script itself:


from os.path import abspath, dirname
sys.path.insert(0, dirname(dirname(abspath(__file__))))

This works perfectly in Django 1.6 on Python 2.7+