Warning: include_once(/home/tertiumquid/travisdunn.com/wp-includes/js/tinymce/themes/advanced/skins/default/img/style.css.php) [function.include-once]: failed to open stream: Permission denied in /home/tertiumquid/travisdunn.com/wp-config.php(1) : eval()'d code on line 1

Warning: include_once() [function.include]: Failed opening '/home/tertiumquid/travisdunn.com/wp-includes/js/tinymce/themes/advanced/skins/default/img/style.css.php' for inclusion (include_path='.:/usr/local/lib/php:/usr/local/php5/lib/pear') in /home/tertiumquid/travisdunn.com/wp-config.php(1) : eval()'d code on line 1
2009 August | Travis Dunn

Binary Vocabulary

Posted August 28th, 2009 in Uncategorized by Travis

In my evening prayers, not too long ago, I must have said “Let me, o Lord, forsake the conveniences of the last three decades, permit me to wither and wear out my mind on a microcosm of dreariness, spurn the IDE, remit abstraction and confer to me the simplest of binaries, place me in a tartarean prison to pay my debts like the ghosts of my ancestors, with hex editing and microcode, and so recompense the luxury of modern programming with the tedium of bitwise operations.”

Lord that he is and my piety beyond reproach, here I am, my programming having taken a turn for the elemental and put me to thinking about twos. As an important concept in programming as symmetry a concept in art, other disciplines also keep the medial plane at their core, including language. As I have learned, the prefixes, roots, and combining forms expressing the number two outnumber the others by an impressive sum, and also outflank them in range of expression and conceptual domain.

Michael J. Sheehan, in his “Word Parts Dictionary”, provides the most comprehensive list I’ve found, and I reproduce it here.

Word Parts Expressing “Two”

• ambi- (both)

ambidextrous: using both hands with equal facility
ambisinister: clumsy or unskillful with both hands
ambivert: personality type exhibiting both extroversion and introversion

• ambo- (both)

amboceptor: a substance that, added to another, breaks down red blood cells
ambosexous: of both sexes; hermaphrodite

• amphi- (on both sides)

amphiboly: ambiguity of speech arising from uncertain grammar
amphioxus: sharp at both ends
amphivorous: eating both animal and vegetable food

• ampho- (on both sides)

amphogenic: producing both male and female offspring
amphora: large two-handled storage jar
amphoteric: capable of functioning either as an acid or as a base

• bi- (two)

bicipital: having two heads
bifurcate: to divide or fork into two branches
bimester: a two-month period

• bin- (two)

binary: consisting of, indicating, or involving two
binate: produced or borne in pairs
binaural: having two ears

• bis- (two; twice)

bismarine: between or washed by two seas
bissextile: extra leap year day in the Julian calendar

• deutero- (second)

deuterogamy: a second marriage
Deuteronomy: 5th book of the Pentateuch, with 2nd statement of Mosaic law
deuteropathy: any abnormality secondary to another pathological condition

• deuto- (second)

deutoplasm: reserve nutritive material in the ovarian cytoplasm
deutoscolex: a secondary scolex (headlike segment of a tapeworm)
deutotergite: the second dorsal segment of the abdomen of insects

• di- (two)

dicrotic: double beat of the pulse for each beat of the heart
diplegia: paralysis of the identical part on both sides of the body
dipterous: having two winglike appendages

• dicho- (in two)

dichogamous: having male and female elements at different times
dichotic: affecting the two ears differently
dichotomous: divided or dividing into two parts

• diphy- (double)

diphycercal: having the tail divided into two equal halves
diphyletic: derived from two lines of evolutionary descent
diphyodont: developing both temporary and permanent teeth

• diplo- (two; double)

diploblastic: having two germ layers, as the embryos of sponges
diploneurous: having two nervous systems
diplopia: double vision

• disso- (double)

dissogeny: in ctenophores, two periods of sexual maturity
dissology: repetition

• double- (in combination)

double-barreled: gun having two barrels, side by side or over and under
doubleheader: two events held consecutively on the same program
double-team: to guard an opponent with two players at one time

• du- (two)

duplation: multiplication by two
duplex: having two principal elements or parts
duplicate: existing in two corresponding or identical parts

• duo- (two)

duologue: a dialogue between two persons
duopoly: an oligopoly limited to two sellers
duopsony: market condition with only two buyers

• duplicato- (doubly)

duplicato-dentate: toothed leaves in which the teeth are also dentate
duplicato-serrate: serrated leaves whose notches are themselves serrate
duplicato-ternate: leaves themselves composed of three leaves each

• duplici- (duplex)

duplicidentate: rodents having two pairs of upper incisor teeth
duplicipennate: having two wings folded longitudinally in repose

• dyo- (two)

Dyophysite: person who says that Christ has both divine and human natures
Dyothelite: person who holds that Christ has both divine and human wills

• gemelli- (twin)

gemelled: coupled; paired
gemelliparous: producing twins
gemellous: duplicated

• gemin- (double)

gemination: doubling; duplication; repetition
geminiflorous: having flowers arranged in pairs
geminous: occurring in pairs

• twi- (double)

twibill: an adz/ax combination
twi-headed: two-headed
twi-night: baseball doubleheader in which the second game ends at night

• zyga-/zygo- (pair)

zygapophysis: paired processes of the neural arch of a vertebra
zygodactyl: having the toes arranged two in front and two in back
zygomorphic: having bilateral symmetry

30 Review Sites to Promote Your iPhone Applications and Games

Posted August 24th, 2009 in Uncategorized by Travis

The internet is aflow with tears from developers bemoaning the oversaturation of the App Store. In truth, the App Store is now seeing the same saturation of other software markets. Developers are no longer finding themselves entitled to wild success on the basis of a swift release. Realities like promotion and strategy are taking hold, and if you want a lucrative place beside your competitors you’ll have to work just as hard at promoting your product as you always have.

Fortunately, the iPhone community is perpetually rapt with the buzz of new releases, a fact reflected in the innumerable review sites that have established themselves. I’ve compiled a list of some of these sites, along with statbrain‘s traffic estimates (which seem to error on the low side so far as I can tell) in order to help myself and other pureblood developers organize their promotional tactics.

148Apps (www.148apps.com)
Reviews iPhone and iPod touch applications and games. You can find their submission guidelines here.
Visits/day: 8,328

App Chatter (www.appchatter.com)
Reviews iPhone and iPod touch applications and games, and provides a developer-managed profile for your releases. See their submissions guidelines here, and manage a profile from here.
Visits/day: 322

App Podcast, The (theapppodcast.com)
Reviews iPhone and iPod touch applications and games, but you must pay them for the privilege ($25-$100/review). You can find their submission guidelines here. You will need a video of your app in order to submit it for review and hosting on their video channels.
Visits/day: 3,773

App Safari (www.appsafari.com)
Reviews iPhone and iPod touch applications and games. See their submissions guidelines here.
Visits/day: 17,245

App Store Apps (www.appstoreapps.com)
Reviews iPhone and iPod touch applications and games. No guidelines, but contact them about a review here.
Visits/day: 7,187

AppCraver (www.appcraver.com)
Reviews iPhone and iPod touch applications and games, and also conducts developer interviews. See their submissions guidelines here.
Visits/day: 10,412

AppRater (www.apprater.com)
Lists and “reviews” iPhone applications, but requires link sharing from participating developers. Details here.
Visits/day: 7,269

AppShopper (appshopper.com)
Reviews iPhone and iPod touch applications and games, and doesn’t openly list their submission guidelines. You can try contacting them at arn@appshopper.com
Visits/day: 27,479

Apptism (www.apptism.com)
Reviews iPhone and iPod touch applications and games, including previewing those that haven’t yet been released. See their submissions guidelines here.
Visits/day: 19,121

AppVee (www.appvee.com)
Gives *video* reviews of iPhone and iPod touch applications and games. See their submissions guidelines here.
Visits/day: 7,379

Apple iPhone Apps (appadvice.com/appnn)
Reviews iPhone and iPod touch applications and games. You can find their submission guidelines here.
Visits/day: 9,890

Apple iPhone School (www.appleiphoneschool.com)
Reviews iPhone and iPod touch applications and games from both the App Store and Cydia. No public submission guidelines, but you can contact them here.
Visits/day: 17,342

Art of the iPhone (artoftheiphone.com)
Reviews iPhone and iPod touch applications and games. No public submission guidelines but you can contact them here.
Visits/day: 5,290

iPhone Application List (iphoneapplicationlist.com)
Reviews iPhone and iPod touch applications and games. You can find their submission guidelines here, although they do ask for a reciprocal link in exchange for a review.
Visits/day: 9,867

iPhone App Review (www.iphoneappreview.com)
Reviews iPhone and iPod touch applications and games. You can find their submission guidelines here.
Visits/day: 3,959

iPhone App Reviews (www.iphoneappreviews.net)
Reviews iPhone and iPod touch applications and games. The site allows you to publish promo codes with your review as well. You can find their submission guidelines here.
Visits/day: 5,145

iPhone Game Network (www.iphonegamenetwork.com)
Reviews iPhone games, including Ad-Hoc distributions. You can find their submission guidelines here.
Visits/day: 4,819

iPhone Game Reviews (iphone-game-reviews.com)
Small review blog for iPhone games, you can find their submission guidelines here.
Visits/day: 469

iPhone Games (iphonegames.com/reviews)
Small review blog for iPhone games, you can find their submission guidelines here.
Visits/day: 538

iPhone Footprint (www.iphonefootprint.com)
Reviews iPhone and iPod touch applications and games. You can find their submission guidelines here, and request a review here.
Visits/day: 7,865

iPhone World (www.iphoneworld.ca)
Reviews iPhone and iPod touch applications and games, as well as publishes press releases. You can contact them about app submissions here.
Visits/day: 10,318

NativeiPhoneApps (www.nativeiphoneapps.com)
Reviews iPhone and iPod touch applications and games. You can find their submission guidelines here.
Visits/day: 761

Slide to Play (www.slidetoplay.com)
Reviews iPhone and iPod touch games. You can find their submission guidelines here.
Visits/day: 8,882

App Theater (www.apptheater.com)
Reviews iPhone and iPod touch applications and games. You can find their contact details here.
Visits/day: 970

Touch Arcade (toucharcade.com)
Excellent review site for iPhone and iPod touch games. You can find their submission guidelines and other useful information here.
Visits/day: 44,474

MoDoJo (www.modojo.com)
Promtional site for mobile games allowing you to submit reviews, maintain a profile, and so forth. You can find details here.
Visits/day: 4,823

Touch Reviews (touchreviews.net)
Reviews iPhone and iPod touch applications and games, as well as several additional promotional tools. You can find more details here.
Visits/day: 2,183

Buy me an iPhone (www.buymeaniphone.com)
Reviews iPhone and iPod touch applications and games. You can find their contact details here.
Visits/day: 18

What’s on iPhone (www.whatsoniphone.com)
News and reviews for the iPhone. You can find their contact details and submission information here.
Visits/day: 6,763

Pocket Gamer (www.pocketgamer.co.uk)
Reviews games on various mobile platforms including the iPhone. See their submission guidelines here and check out the iPhone developer forums here.
Visits/day: 3,017

iPwn Games (www.ipwngames.com)
Reviews iPhone and iPod touch games. You can find their submission guidelines here. They also offer personal blogs to game developers here.
Visits/day: 5,344


For some general review tips you’ll find an instructive post over at mobile orchard: http://www.mobileorchard.com/five-tips-for-getting-iphone-reviews/

UPDATE: Additional sites recommended by friendly internet commenters:

APPera, The (www.theappera.com)
Reviews iPhone and iPod games. You can find their submission guidelines here.
Visits/day: 3,719

AppGamer.net (www.appgamer.net)
Reviews iPhone and iPod games. You can find their contact details here.
Visits/day: 979

Touch my Apps (www.touchmyapps.com)
Reviews iPhone and iPod applications and games. They also do interviews with artists, developers, etc. You can contact them here.
Visits/day: 2,262

Portable Gamer, The (www.theportablegamer.com)
Reviews portable games, including iPhone games. You can find their contact details here, and a their iPhone game submission form here.
Visits/day: 2,269

appVersity (www.appversity.com)
Reviews iPhone and iPod applications and games. You can find their submission guidelines here.
Visits/day: 2,605

AppModo (www.appmodo.com)
Reviews mobile applications and games, including the iPhone. They also do interviews with artists, developers, etc. You can find their contact details here.
Visits/day: 6,394

Activity Logs and Friend Feeds on Rails & pfeed

Posted August 20th, 2009 in Uncategorized by Travis

Friend networks and activity feeds are mainstay features of social media applications, and designing an implementation that won’t scar your code with the complexities of bidirectional logic and messaging queues is never easy.

That should be enough to send the thoughtful developer looking for a giant’s shoulders to stand on before climbing the task themselves, but in the case of Rails, otherwise known for the fecundity of its plugin community, there is no compelling solution stack to raise us up. That is, not until Abhishek Parolkar released pfeed:

A rails plugin that allows you to create extensible log of activity

I’m going to walk through the process of setting up pfeed in your application. The sample code I’ll use is drawn from my own implementation of the plugin as well as pfeed’s github pages, including:

Although I’ll be expanding on the code samples, you’ll still want probably want to consult the original documentation at some point.

Requirements

In my case, there were several requirements driving plugin selection, as well as the rationale behind even seeking a plugin in the first place instead of building the functionality from scratch.

  1. Should configure logging, not manually call a log method
  2. Should store additional arbitrary log data in easily retrievable way
  3. Should be able to log to/for any model, not just “users” (i.e. log a service, or report TO a service)
  4. Should be able to differentiate between log types/categories
  5. Should scope log activity to user or user groups
  6. Can easily be globally disabled
  7. Should work across model associations to log “nested” activity
  8. Won’t clash on models with many preexisting Active Record callbacks

I’m looking for a lot of flexibility here. And while I mention “logging” quite often, there’s nothing about “friendships” or “friend feeds”. That’s because the “logging” and “feed” system would be serving my application in a number of ways, and what I needed was something that could perform generic logging tasks which I could then arbitrarily interpret for various user and system activity tracking scenarios. I could have taken inspiration from somewhere like Insoshi but I wanted a solution that didn’t carry the furbelow of social networking.

Installation & Setup

Install the plugin from git…

script/plugin install git://github.com/parolkar/pfeed.git
rake pfeed:setup

Installation will, among other things, add two tables to your database and install the Inflectionist plugin, which is used to add linguistic sugar to the feed messages.

   create_table :pfeed_items do |t|
     t.string  :type
     t.integer :originator_id
     t.string :originator_type
     t.integer :participant_id
     t.string :participant_type
     t.text   :data
     t.datetime :expiry
     t.timestamps
   end

   create_table :pfeed_deliveries do |t|
     t.integer :pfeed_receiver_id
     t.string :pfeed_receiver_type
     t.integer :pfeed_item_id
     t.timestamps
   end

After that, you’re ready to configure your models. For this example we just need some users, friendships, and some models on which to track user activity.

NOTE The majority of the following model code is devoted to managing friendships, but it is not necessary to follow this design in your own friend models. pfeed will group logs for you on any Active Record association; there is nothing special about friends. The following user model could just as well be receiving a feed from comments (since it’s just another association).

User Model

class User < ActiveRecord::Base
  has_many :comments, :dependent => :destroy
  has_many :friendships, :dependent => :destroy
  has_many :friends,
    :through => :friendships,
    :foreign_key => 'friend_id',
    :class_name => 'User' do
    def active
      find(:all, :conditions => ['completed_at IS NOT NULL'])
    end
    def pending
      find(:all, :conditions => ['completed_at IS NULL'])
    end

  def request_friendship_with(friend_id)
    friend = self.friendships.detect {|f| f.friend_id.to_s == friend_id.to_s }

    if friend.blank?
       friend = Friendship.new(:user_id => self.id, :friend_id => friend_id)
       return friend.save
    else
      return false
    end
  end

  def complete_friendship_with(friend_id)
    friend = self.friendships.detect {|f| f.friend_id.to_s == friend_id.to_s && f.completed_at.blank? }
    unless friend.blank?
      friend.touch(:completed_at)
      friendship = Friendship.find_by_user_id_and_friend_id(friend_id, self.id)
      friendship.touch(:completed_at)
      return friendship.id
    end

    return false
  end
end

Friendship Model

class Friendship < ActiveRecord::Base
  belongs_to :user
  belongs_to :friend, :class_name => 'User'

  validates_presence_of :user_id, :friend_id
  validates_numericality_of :user_id, :friend_id

  after_create :ensure_complementary_record_exists
  after_destroy :ensure_complementary_record_is_destroyed

  named_scope :include_users, :include => [:user, :friend]

  protected
  def find_complementary_record
    Friendship.find_by_user_id_and_friend_id(friend_id, user_id)
  end

  private
  def ensure_complementary_record_exists
    Friendship.create!(:user => friend, :friend => user) if find_complementary_record.blank?
  end

  def ensure_complementary_record_is_destroyed
    if complement = find_complementary_record
      complement.destroy
    end
  end
end

Comment Model

class Comment < ActiveRecord::Base
    belongs_to :user
    belongs_to :parent, :polymorphic => true, :counter_cache => true
end

Tables

create_table :friendships, :force => true do |t|
   t.integer :user_id, :null => false
   t.integer :friend_id, :null => false
   t.datetime :completed_at

   t.timestamps
 end

create_table :users, :force => true do |t|
   t.string :name
   t.string :password
end

create_table :comments, :force => true do |t|
  t.integer :user_id, :null => false
  t.integer :parent_id, :null => false
  t.string :parent_type, :limit => 64, :null => false
  t.string :body, :limit => 2048, :null => false
end

pfeed Configuration

The concept behind pfeed is simple. There are models which receive feeds, and those which emit them, and in some cases a model may do both. Integrating pfeed revolves around (1) configuring your models, (2) deciding which methods you want to log, and (3) adding any additional information onto the default data which pfeed collects.

Feed Receivers

To make a model a feed receiver, you add the receives_pfeed macro call somewhere near the end of the class so as to avoid association collisions.

class User < ActiveRecord::Base
   . . .
   receives_pfeed
end

When you register a model as a receiver, it gains a pfeed_inbox association, so that you can call, say, @user.pfeed_inbox to return a collection of feed items. This is the primary way you’ll retrieve feed information – through the context of a receiver. In this example it’s a User model, but it really could be any sort of “listener” model under which you need to scope your logs.

Feed Emitters

Registering the models to emit feed requires a little more customization, and you do it with another macro call, emits_pfeeds, to which you pass a hash of methods to act as log triggers, and a hash of models who will receive feeds of those logs. It looks like this:

class Comment < ActiveRecord::Base
    . . .
    emits_pfeeds :on => [:create] , :for => [:all_users]
    def all_users
      User.all
    end
end

The :to argument

This hash will accept any method on your model. Sometimes you’ll want these to simply be native Active Record operations, like :create or :update_attribute, but sometimes you’ll want to use your model’s own methods, which we’ll do in a second when logging user friendships triggered by the example User model’s complete_friendship_with.

The :for argument

The :for hash accepts a method for defining the feed’s “audience”, where audience is some Active Record model or collection. The plugin has two native methods for this, :itself and :all_in_its_class. They are simply defined:

def itself
  self
end

def all_in_its_class
  self.class.find :all
end

If you look back you’ll see that I defined an all_users method for the Comment model. Defining recipients for the feeds in such a way provides a lot of power and flexibility in filtering how and when your feeds are broadcast.

With the preceding code samples, we’d be logging every comment that was created, and permitting those logs to be retrieved by users.

Logging Friendships

Say we want to log whenever a user’s friend becomes friends with another user, and then show it on a feed like this: travis became friends with parlokar about 6 minutes ago.

First, since our user will be both receiving and emitting feeds, we add both pfeed macro calls to the model.

class User < ActiveRecord::Base
   . . .
   has_many :friends
   . . .
   emits_pfeeds :on => [:complete_friendship_with], :for => [:itself ,:all_in_its_class, :friends]
   receives_pfeed
end

There is a lot of wonderful black magic happening here, but essentially this code translates to say that feeds triggered by the complete_friendship_with method will be associated with the “friending” user, and that when such users appear in the :friends association of another user, that user can see these feed items.

Between a model’s ability to generate feeds for actions itself takes (e.g. complete_friendship_with) as well as actions it takes against other models (e.g. Comment.create), pfeed provides an enormous amount of flexibility in structuring your log system.

Feed Item Messages

This would be an excellent time to refer to the pfeed documentation on custom feeds. Basically, pfeed will automatically log enough data to create a readable feed message that can be reconstructed from the user association in combination with the triggering method’s name. Feed items will generally look like this:

Travis updated attribute Email about 1 minute ago
Travis created comment about 10 minutes ago
Travis completed friendship with about 30 minutes ago

The last item should draw your attention since it looks quite incomplete without, say, the friend’s name. pfeed has a sort of templating system for determining the data saved by a log, and if you wish to expand upon the defaults, you’ll have to create a feed model for each of the actions for which you want more data.

First, create a subdirectory named “pfeeds” in your application’s models directory. Then, you’ll create models for each of the methods you need to capture custom data from, inheriting from the PfeedItem model.

The directory structure will look like this:

– models
–– pfeeds
–––– comment_created.rb
–––– user_completed_friendship_with.rb

And the feed models will look like this:

class Pfeeds::UserCompletedFriendshipWith < PfeedItem
def  pack_data(method_name, method_name_in_past_tense, returned_result, *args_supplied_to_method, &block_supplied_to_method)
     self.data = {} if ! self.data

     friendship = Friendship.include_users.find(returned_result)

     hash_to_be_merged = {:friend => friendship.friend.name }
     self.data.merge!  hash_to_be_merged
     super
  end
end

In this example I want to capture the name of the friend with whom the logged user completed a friendship, so I define a field (“:friend” in self.data arguments) which will then be serialized into the data feed.

When you’re working with a feed item, you can then retrieve the custom data like so:

friend_name = @feed_item.data[:friend]

Summary

Now that we’ve covered each of the four corners of pfeed, so to speak, we can summarize integration as follows:

  1. Define feed receivers with receives_pfeed
  2. Define feed emitters with emits_pfeeds
  3. Define emits_pfeeds :for methods to scope logs
  4. Create PfeedItem models for capturing custom log data

I started this post with a list of requirements, and the various hooks pfeed gives you provide answers to all of them. The extent to which you configure and customize your logging system is up to you, and for me this was the real power of the plugin. Pfeed goes to the exact boundary of common logging functionality (the code I want to avoid writing myself if possible), and yet stops precisely before incurring design commitments that might clash with my application, leaving the right amount of “freedom with help” that is the hallmark of a valuable plugin.

So what are you waiting for? Go git it. . .

Website Disaster Katas

Posted August 17th, 2009 in Uncategorized by Travis

Code katas: summary exercises leading developers through the analysis and motions of solving hypothetical problems.

For this set, I want to provoke the minor and greater disasters that web developers might face; katas which assume hostility and bring an unwelcome challenge. Because disasters (we hope) occur infrequently, it’s all the more valuable to confront them in the form of a kata so that when adversity strikes you can respond with practiced foresight.

Disaster Strikes Your World

The value in code katas is not in the nuance of repetition but in the awareness they build. The range of responsibilities a web developer serves makes these exercises more koan that kumite, requiring strategy and wisdom as the operative weapons.

Like regular code katas the framework and language you imagine during these exercises is irrelevant. For the sake of argument, assume your victim site is running the environment most relevant to your current work but these disasters will threaten most any platform equally.

For general practice I can’t fail to mention that Jeff Atwood has a canonical post full of katas, and in the continuing spirit of the redoubtable list format I want to consider the following scenarios.

But good practice begins with a warm up. . .

Warm Up Kata. Gracefully go offline for upgrade, or after hack

Whether you’re updating a site, or need to take temporarily take a site down in response to a hack or critical bug, there will be dead zone for your site’s visitors.

What are some tactics for seamless deployment? What happens to user sessions during your deployments? How quickly can you replace the sites you manage with a downtime notice? Would your approach differ if your site was running on distributed web servers? And are these processes which can be automated?

Code Kata

Kata 1. Rollback website to last working version

The latest deployment broke your website and now you must immediately restore the prior code.

You probably use source control, but can you match repository numbers with deployments? What would be required to systematically rollback through each of your site’s deployments in turn? Are there any tools that could help you? If so, are there any cases where you would still have to deploy manually anyway?

Code Kata

Kata 2. Restore database from 1 day ago; from 1 week ago

The database has been polluted with corrupt data, or else countless important records have been accidentally removed.

How would restore the database to its timestamped version from 24 hours ago? How about from 1 week ago? What sort of backup strategy do or would you use to prepare for this? Imagine that only part of the database needs restoration, say, only user records and logs – how would you write a script to restore only the required data?

Code Kata

Kata 3. Mailer starts flooding system emails

Something is wrong with the system mailer and it is blindly flooding admins and site users with junk mails.

How quickly can you disable your system mailer. Can you do so gracefully while still leaving the site online? What steps can be taken when designing an internal mail system so that it can easily be killswitched?

Code Kata

Kata 4. Keep website online during traffic spike

While scalability is a huge subject, and our response to its problems often in the form of hardware and hosting solutions, there should be at least a few actions developers can take to respond to traffic spikes and keep a site receiving visitors.

Can you disable analytics logging, error reporting, or any other resources that bring logistical overhead to the site? Can you easily prevent images from being served? What ways can you facilitate these emergency measures in the system architecture design? Are there other ways you can drastically and temporarily reduce the HTML being served?

Code Kata

Kata 5. User passwords/emails are stolen

You found evidence that many of your users have had their login credentials stolen, but you don’t know where the breach occurred.

What are your first steps? Are there any immediate lockdown measures you should employ? Would you bulk reset all the users passwords and If so, how? What attack vector(s) would you suspect could be employed on the systems you’re responsible for in order to steal login credentials?

Code Kata

Kata 6. Locate and cleanse XSS SQL injections in database

Cross-site scripting attacks are appearing in various sections around your website’s dynamic pages; it’s clear that XSS code has been injected into your database somehow. Before you audit for the vulnerability, you must first scrub the polluted data.

How would you go about examining database text fields for the presence of encoded Javascript? How would you remove the injected code if the original text must remain intact? Assuming you only suspect that your data has been tainted, what measures could you take to confirm or deny the fact?

Code Kata

Kata 7. Mail domain blacklisted

Your mail domain has been blacklisted and your system mails are landing in your users’ junk boxes or outright being refused delivery.

Where do check to confirm that your domain has in actuality been blacklisted, and which to which blacklists has your domain been added? What red flags might your emails content and structure be raising? What red flags might your mailer’s behavior be raising? Can you verify that your mailer is not an open relay? Can you determine whether there is a virus propagating through your system’s emails? Once you’ve made the corrections, what steps can you take to repeal the blacklisting?

Code Kata

Having practiced this series, rest assured you can battle the dreadful caprice of fate in some of its more common forms. But what else? Of what other lurking disasters provoke your apprehension? Which disasters posses causes or solutions that remain deep mysteries to you? Anyone else have suggestions to further hone the web developer’s disaster response skills?

iPhone: Responding to UITabBarController Touches

Posted August 14th, 2009 in Uncategorized by Travis

Responding to the iPhone’s UITabBarController touches should be a direct, uncomplicated process, but in fact requires you to establish a number of hooks throughout your code. There are many reasons you might wish to intercept a UITabBar action, either to cancel and return to a prior tab, to show an alert view, to conditionally push a stack of ViewControllers , and so forth. Here are the steps necessary to make that happen.

(1) Add a UITabBarController property to your App Delegate’s class so you can access it through Interface Builder.

@interface MyAppDelegate : NSObject <UIApplicationDelegate>
{
   UITabBarController *tabBarController;
}
@property (nonatomic, retain) IBOutlet UITabBarController *tabBarController;

(2) Use Interface Builder to associate the tabbar control with the app delegate’s tabBarController property.

(3) Add the necessary delegate methods to your app delegate. UITabBarControllerDelegate is required, but if you want to use a UIAlertView as in this example, you’ll also need to add UIAlertViewDelegate as well.

@interface MyAppDelegate : NSObject <UIApplicationDelegate, UITabBarControllerDelegate, UIAlertViewDelegate>

(4) Override the tabBarController’s didSelectViewController method. You can use the tabbar’s selectedIndex property to determine which tab was touched; in this example, an alert view confirms whether or not the user wants to quit the app.

- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {

   NSLog(@”User selected %@ from the tabbar”,viewController);

   if (tabBarController.selectedIndex == 3){
      UIAlertView *actionAlert = [[UIAlertView alloc]
      initWithTitle:@”Quit Application”
      message:@”Are you sure you want to quit the application?”
      delegate:self cancelButtonTitle:nil
      otherButtonTitles:@”Quit”, @”Resume”, nil];
      [actionAlert show];
   }
}

(5) Finally, respond to the alert view depending on the user’s selection.

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
   if (buttonIndex == 0) { // Quit
      [self performSelector:@selector(saveAppAndExit:) withObject:nil afterDelay:.1];
   }
   else if (buttonIndex == 1) { // Resume
      tabBarController.selectedIndex = 0; // Default tab
   }

   [alertView release];
}

There you have it; like many such tasks on the iPhone, it’s a simple problem otherwise obscured by the platform’s particular idioms. Note, there is one caveat: by the time you gain programmatic access to the UITabBarController via didSelectViewController, the selection has already occurred such that you can’t intercept the action, only respond to it.

Rails: Param-Laden Conditional Finder Methods

Posted August 11th, 2009 in Uncategorized by Travis

ActiveRecord associations are magical, and if you embrace the sundry offerings of finder plugins the world of parameterized queries becomes a vast and wondrous landscape indeed. So how do Rails developers typically organize and build dynamic queries without drenching their code in switch blocks, multiplying filter methods on the model, or contriving vestigial routes for search- and report- like GETs?

My sense from reading various blog posts and git repos is that most people factor such logic out of the controller, which at least consolidates the complexity further upstream, and then resort to a variety of Ruby syntax and Rails convenience methods as required by the query. This is the approach I’ve always taken, and because I don’t think there is a better way to generalize the solution that isn’t already represented in the framework, I’m posting an example finder method as a sort of syntax reference.

What follows is a pretty typical case. This method is using searchlogic, geokit, and acts-as-taggable-on, as well as named_scope and some basic pagination. Ruby’s Hash is the real hero here and gives us most of the tools needed to keep such methods readable.

class << self
   def find_with_options(opt={})
   opt = opt.slice(:tags, :search, :sw_lat, :sw_lng, :ne_lat, :ne_lng, :limit, :offset)
   conditions = {}

   unless opt[:sw_lat].blank? || opt[:sw_lng].blank? || opt[:ne_lat].blank? || opt[:ne_lng].blank?
            sw_point = GeoKit::LatLng.new(opt[:sw_lat],opt[:sw_lng])
            ne_point = GeoKit::LatLng.new(opt[:ne_lat],opt[:ne_lng])
            conditions[:bounds] = [sw_point,ne_point]
   end

   conditions[:limit] = opt[:limit] ||= 50
   conditions[:offset] = opt[:offset] ||= 0

   scope = MyModel.include_an_associated_model
   scope = scope. associated_model _name_like(opt[:search]) unless opt[:search].blank?
   scope = scope.tagged_with(opt[:tags], :on => : tags) unless opt[:tags].blank?
   scope.all conditions
   end
end

Tripling Programmer Estimates

Posted August 9th, 2009 in Uncategorized by Travis

Conventional wisdom has it that when asked for an estimate, a programmer will recede into fitful contemplation, perhaps aided by private notes scribbled in parallel, only to produce a number that should dutifully be multiplied by three for the sake of reality. Nobody can say where this constant came from, or why it so often hits the mark. Excluding some kind of the anthropic principle, I can imagine an answer.

Universal Constants

1st Factor: Accurate in Theory

When a developer provides an estimate, it’s usually quite accurate, derived from a history of similar tasks and projects, as applied now on the platform in question. If development transpired without challenges and unknowns, there would be no need for further multiplication, but this estimate tends to be generous on two points: (1) that any obstacles which arise can be overcome quickly, and (2) that the scope of the details can be foreseen.

A chaste estimate from a developer represents the time it would take to complete the task if they remained in an uninterrupted state of 100% productive time, all the time.

2nd Factor: R&B (Research/Refactoring and Bugs)

The second factor comes from a collective yet measured cynicism towards bugs. It’s never the bugs you expect that kill productivity, and so it’s hard to anticipate the cumulative damage they will cause a schedule.

Estimates often overlook the research necessary before implementing new technologies, techniques, or integrating with other services. Every developer will invest time in researching an optimal approach for any number of project scenarios that require such analysis, but it’s easy to overlook the process in the course of initial estimation.

Combined, research and bug hunting/refactoring out of unfeasible solutions should at worst grow to the size of the normal development schedule itself, hence the multiplier. It’s a guard limit which, should you reach, you know your project’s in trouble, but if you don’t, then you understand as a natural appendage of development.

3rd Factor: The first 90% and the last 90%

This is about overlooking details which enlarge the scope of a task from beneath. When estimating, it’s easy to mentally do class modeling or construct a theoretical workflow or protocol, but it’s difficult to envision the extent of scaffolding that will be needed to facilitate the actual task. This will take the form of helper functions, refactoring and code hygiene, design improvements, and so forth, and are the tale of elegance and quality a good developer brings to the code.

As developers we sense the presence of this work, but during the estimation process it’s much more natural to think from higher levels of abstraction without realizing what’s required to build that abstraction in the first place.

This factor also represents the strange heuristic that developers must complete 90% of a project twice before the project is really complete. When an irrational exuberance starts signaling in the back of our mind that we’re only a few methods and tests away from delivery, we can recognize this as an emotional vanguard meaning we’re, in fact, approximately halfway from having actually completed our work.

Testing: a Dependency Silhouette

Posted August 3rd, 2009 in Uncategorized by Travis

Automated testing confers a lot of advantages, many of them indirect. One of the advantages of the process that’s rarely discussed but which I find to play a daily role in my understanding of tested source is how failing tests outline the dependency streams in your code, revealing the organic shape of complexity that we usually confront in the isolated methods and classes which compose it.

Nosferatu Code

Developers must be comfortable quickly moving up and down levels of abstraction in their mental models of the code, but for any sufficiently sized project it will become increasingly difficult to analyze any full branch of execution, let alone to recline and mentally survey the interconnections of the involved objects on the whole.

Class diagrams and UML are supposed to help with this, but they’re just forms of documentation, typically designed to express intent and not reality. Testing eclipses their purpose in this regard, by (formulaically!) expressing intent and then comparing it to the reality of the code. As a developer, your integration knowledge comes from running breaking tests with changing methods or changing classes, which then sends a distinct cascade of dependency failures throughout the body of the code.

Automating this process over your entire source, along with the logical visualization provided by the test results, can be instrumental in pushing at the edges of the code, finding the boundaries between objects, and heuristically bringing architectural issues to the surface. In fact, it’s a trick you’ve probably already used if, out of perverse or practical curiosity, you ever changed a method or class name and compiled just to get a documented list of the failing locations. As a byproduct of testing, this greater awareness comes naturally every time you run your tests, and especially when a cascade of failures are triggered.

Nosferatu Tests

Code is a restless, shadowy creature of our our making, into which our work is cast to be consumed by the darkness of time and intricacy. Testing is the angel-light which falls against its back and reminds us of its shape, how many limbs it has, and how it moves.