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 July | Travis Dunn

Rails: polymorphic belongs_to associations with accepts_nested_attributes_for

Posted July 31st, 2009 in Uncategorized by Travis

If there is a combinatorial way to bring aspects of a framework together in a breaking edge case, I will find that way and take that step. It’s a destiny one follows gladly; an instinct useful in defining the boundaries of an application’s logical complexities as they accumulate on the brain like bit patterns. It makes you wade through limitations, leading to unexpectedly serviceable workarounds.

The problem for me, at least, is that I can’t turn the compulsion off. It sits right below my consciousness, urging the brain, when given a system, to seize upon the most elegant paradox it detects for solving the problem at hand. Take, for example, polymorphic belongs_to associations with accepts_nested_attributes_for in Rails. Any two of these keywords in combination will turn up tales in the SERPs of bewilderment and errors, but the effort to solve a data modeling problem brought these three elements together in a perfect storm that would punish me for my inspiration.

So I’ve one model, which then belongs_to another, polymorphic, model. The belongs_to model was the workhorse of the pair, and therefore needed to accepts_nested_attributes_for in order to initialize its counterpart as required.

class BelongsToModel < ActiveRecord::Base
   belongs_to :polymorph_model, :polymorphic =>true
   accepts_nested_attributes_for :polymorph_model
end

Unfortunately, what appears to happen when one puts this design into practice is that a NoMethodError is thrown whenever the belongs_to model receives the nested attributes hash, e.g.

params = {
   :name => “blah”,
   :parent_type => “polymorph_obj_class”,
   :polymorph_model_attributes => {
      :info => “blah”,
      :details => “blah”
   }
}

@belongsToModel = BelongsToModel.new(params)

In the example, polymorph_model_attributes is constructed with the attributes “info” and “details” because I personally have the domain knowledge to know that those attributes belong to the polymorph model and should be provided. To process nested attributes, however, Rails needs to know this also so it can use that knowledge to add an appropriate build method (called something like ‘build_polymorph_model ‘) to the belongs_to model, and initialize the nested object whenever the belongs_to model is initialized.

The paradox arises because Rails cannot dynamically create a “build_polymorph_model” method without first knowing the class of the polymorph. Even passing in a parent_type or equivalent attribute will not provide the model with the foreknowledge it needs to build this helper method.

Any alteration to my data model would be enough to escape the conflict, but this uncomfortable relationship with belongs_to and the need to instantiate my objects from the direction of the belongs_to model came about because it really does best represent the schema behind the scenes, and so I was loathe to surrender it to the apparent constraints.

The solution was as simple as possible. I took a literalist approach, and went ahead and defined the build_polymorph_model explicitly myself, adding in the appropriate logic to initialize any one of the several possible polymorphic models that could be associated.

class BelongsToModel < ActiveRecord::Base
   belongs_to :polymorph_model, :polymorphic =>true
   accepts_nested_attributes_for :polymorph_model

   def build_polymorph_model(params)
      # build any supported polymorphic relationships here
   end
end

iPhone Guidelines and Resources for Artists

Posted July 28th, 2009 in Uncategorized by Travis

The Basics

Screen Resolution: 320×480 (or 480×320 landscape mode)
Colors: 262,144
Resolution: 160 dpi
Contrast: use higher contrast than normal for art on the iPhone screen
Preferred Graphics Format: .PNG

Fairlady Media has a great instructional post covering a variety of topics about creating iPhone graphics: http://fairladymedia.com/node/10

Application Logo and Icon

In order to distribute an application in the App Store, Apple requires two main  graphics:

(1) A large 512×512 logo, and;

(2) a smaller 57×57 version of the same.

The small logo must resemble the large logo, although there can be minor differences in perspective and detail, or the application may be rejected for inconsistent logo design. The 512×512 logo is what people see when they are browsing iTunes, while the 57×57 logo will be the application’s icon on the iPhone itself.

The App Store and the iPhone will apply additional effects to the app logos by rounding the corners and applying a light gloss. One of the tasks when designing a logo is to ensure that it will look good with the iPhone effects applied.

The Tabbar

The tabbar is a native UI element displayed at the bottom of the screen. Each tab button may contain text and an icon. The following guidelines apply for tabbar icons:

  • Use the PNG format.
  • Sized 30×30 (roughly – you have a little leeway, ~25-35)
  • Use pure white with appropriate alpha
  • Do not include a drop shadow.
  • Use anti-aliasing.

There’s a painstakingly informative tutorial at Osmorphis about the process of creating tabbar icons (summary here), but the thing that deserves special attention is that the icons must be drawn in B&W alpha, and in negative. The Osmorphis tutorial covers the steps on how do this pretty efficiently in Photoshop.

Layout, Templates, Mockups

The following PSDs contain templates and native iPhone UI elements that you can use as building blocks for your mock ups.

iPhone GUI PSD
http://www.teehanlax.com/blog/?p=1628

iPhone Kit
http://andrewbadger.deviantart.com/art/iPhone-Kit-108089727

Resizable iPhone Shell PSD
http://twotoasters.com/index.php/2009/06/02/resizable-iphone-psd/

Fonts

These are the standard iPhone system fonts available. It’s much harder than it should be to use a custom font on the iPhone.

American Typewriter, AppleGothic, Arial, Arial Rounded MT Bold, Arial Unicode MS, Courier, Courier New, DB LCD Temp, Georgia, Helvetica, Helvetica Neue, Hiragino Kaku Gothic ProN W3, Hiragino Kaku Gothic ProN W6, Marker Felt, STHeiti J, STHeiti K, STHeiti SC, STHeiti TC, Times New Roman, Trebuchet MS, Verdana, or Zapfino.

Colors: 262,144

Named Branches: Logic to the Word

Posted July 23rd, 2009 in Uncategorized by Travis

Comments and self-documenting code are like brandy and cigars, the first illuminating your source (meaning both the gentleman’s soul and the source code into which he pours it), and the second imparting a blazing instance of clarity where you can taste the meaning.

Brandy and Cigars

Adherents debating the styles travel parallel roads in the direction of improving maintainability, but take opposing paths (and tend to toss aspersions across the median). Comments depart from reality over time and are perhaps redundant by nature, while self-documenting code is a frequent vanity and incapable of reflecting the many levels of abstraction that constitute design. I think a good way of realistically traveling these issues is by practice, and naming your branch conditionals (the subject I raise this very moment!) is a modest but noble idiom suitable for any lounge in solitude or with a cordial in hand.

Branch conditionals are important thing to name right because they’re all but the core flow of your code and you’ll be reading them over and over again in the repetitive quest for understanding, and its more senile relative, recollection. Branch conditionals (usually) look like this:

If (x && (y = (d  ? a : b) || y < e.p() ) )
{
blah();
}
else if (t.F() && g == q[0])
{
meh();
}

A far more readable and self-documenting way to formulate the code would simply be:

var isThisThingAndAlsoSomethingElse = (y = (d  ? a : b) || y < e.p() );
var butThatCouldAlsoBe = t.F() && g == q[0];
If (isThisThingAndAlsoSomethingElse )
{
doThis();
}
else if (butThatCouldAlsoBe)
{
doThat();
}

I find the separation of the comparisons from their consequences to save hundreds of milimoments of thought when working with code. Like most advice, it’s quite simple, and nobody follows it. The highest value can come from small optimizations like this, and collectively, when I scroll through source code with a lot of named booleans I read it that much faster than short files with pithy dents of anonymous conditionals.

In fact, I find this simple idiom useful enough that if I were granted one wish about all the code I’m to read before I die, well, named branches would be the second after the simple demand for thoughtful, verbose variable names, of which named branches is a like subset to begin with so it’s reasonable several times over.

A fortunate byproduct this practice is that naming branch conditionals can sometimes be hard, a fact you should use as a chance to articulate your logic. Choosing a name can also be a useful secondary measure of code smell, or suggest method refactoring, or reveal problems with business logic, and what’s more it’s a further refinement in this world of programming where nouns and verbs are given descriptive titles yet filled with murky details.

So what you have is self-documenting code because it reads like a comment, and it must read like a comment in order to express a more or less complex branch conditional. At a higher level, idioms like this are showing up in a lot of other places like Domain-Specific Languages and advice on naming tests, which are arguably just a branch conditional at heart themselves. What that suggests to me is that it’s a useful detail for programmers to orientate to.

Benefits: readability; passive analytical tool; DRY.
Costs: verbose; antagonizes our instinct for quick and clever over clear.

Evolutionary Wonders That Shaped the Computing World

Posted July 20th, 2009 in Uncategorized by Travis

The axe and the knife are considered the most important inventions in human history. What are the software equivalents? With software, there’s a blur between the conceptual (something like Formal Logic) and the actual (an IDE), so it’s harder to answer this question as categorically as I would like without broadening the boundaries to computing in general. Never deterred by inadequate specs, however, a few candidates come to mind:

Compilers: the process of transforming one high-level language into a low-level equivalent is vital in enabling the rapid advancement of computing and lowering the barriers to entry to the point where programmers actually constitute a large workforce instead of rare specialist interest.

The Internet: not exactly software, but the collection of protocols which qualify it under the fluid non-definition given above. I have to swear by the dissemination of information and communication and information harvesting as pivotal enablers in software development.

Public key encryption: the Internet and peer communication in general would be decisively hobbled were in not for the ability to establish trusted relationships between computers.

The OS: bootstrapping and a run-time environment for assembly files are indispensable to both user and developer alike, lowering development and usage skill barriers to the point where computing could actually become a public industry.

The GUI: Mouse- and windows-based interfaces have not only accelerated the speed at which we can use computers, but transformed our mental conceptualizing of the abstract relationships in information technology.

Leibniz, Letter to Duke of Hanover, 1679

Posted July 16th, 2009 in Uncategorized by Travis

Leibniz gives a wicked elevator pitch for some new technology he’s working on…

Gottfried Wilhelm Leibniz

If only God would again inspire your Highness, the idea which had the goodness to determine that I be granted 1200 ecus would become the idea of a perpetual revenue, and then I would be as happy as Raymond Lull, and perhaps with more reason. . . . For my invention uses reason in its entirety and is, in addition, a judge of controversies, an interpreter of notions, a balance of probabilities, a compass which will guide us over the ocean of experiences, an inventory of things, a table of thoughts, a microscope for scrutinizing present things, a telescope for predicting distant things, a general calculus, an innocent magic, a non-chimerical cabal, a script which all will read in their own language; and even a language which one will be able to learn in a few weeks, and which will soon be accepted amidst the world. And which will lead the way for the true religion everywhere it goes.

- Leibniz, Letter to Duke of Hanover, 1679

“I’m begging you, let me work!”

Posted July 5th, 2009 in Uncategorized by Travis

Those were the dying words of legendary Osamu Tezuka, father of artforms and a man whose reaching influence on today’s symbols, pop culture, and storytelling is difficult to overstate.

Osamu TezukaWhen work is playful and creative vision makes labor effortless, you can understand how pure a statement Tezuka made if you replace the word “work” with “live”. Maybe it would be appropriate here to call him by his Buddhist name, Hakugeiin Denkakuenju Shodaikoji, parting earth with such an elegant abstraction on the human condition. 八(^□^*)