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
Code | Travis Dunn - Part 2

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

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

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.

Rails: Getting Youtube Video Information in XML

Posted May 22nd, 2009 in Uncategorized by Travis

Here’s another little Rails code snippet for getting video details, this time from Youtube. The code simply retrieves an XML details object for a given video. Enjoy. . .

YOUTUBE_URL_REGEX = /(www.)?youtube\.com\/watch\?v=([^&]*)/i
url = http://www.youtube.com/watch?v=az-8Z1skhLs&feature=channel_page

begin
if YOUTUBE_URL_REGEX.match(url)
vid_id = YOUTUBE_URL_REGEX.match(resource_locator)[2]
youtube_url = "http://gdata.youtube.com/feeds/api/videos/#{vid_id}"

response = Net::HTTP.get_response(URI.parse(youtube_url))
results = Hash.from_xml(response.body)

@description = results["entry"]["group"]["description"]
@thumbnail_url = results["entry"]["group"]["thumbnail"][0]["url"]
end
rescue Exception => exc
# DNS failed...
end

See also: Getting Vimeo Video Information in JSON

Rails: Getting Vimeo Video Information in JSON

Posted May 19th, 2009 in Uncategorized by Travis

Here’s a little Rails code snippet, posted here for posterity or until Vimeo changes their developer API. The code simply retrieves a JSON details object for a given video. Enjoy. . .

VIMEO_URL_REGEX = /(www.)?vimeo\.com.*?\/(\d+?)$/
url = "http://www.vimeo.com/2233379"

begin
if VIMEO_REGEX.match(url)
vid_id = VIMEO_URL_REGEX.match(url)[2]
vimeo_url = "http://vimeo.com/api/v2/video/#{vid_id}.json"

response = Net::HTTP.get_response(URI.parse(vimeo_url))
results = JSON.parse(response.body)[0]

@description = results["description"]
@thumbnail_url = results["thumbnail_small"]
end
rescue Exception => exc
# DNS failed...
end