Cheap O’Reilly pocket references. Enough to make you sew on extra pockets. Also the word pocket is funny.

No Comments »

So the fantastic O’reilly is having a sale with pocket reference books for $4.99. While I know books belong in the hellish past with plagues, famine and bakelite, ebooks are searchable, DRM free and available for life. At least, these ones are. They’re great at saving you from wading through 43420423 posts asking your question and getting crappy replies on Stack Overflow. At my count there’s 89 of them, which means if you’re interested in everything from Vi to PowerShell to XML to Knoppix, you can save … err … quite a bit. Yeah.

Enough for some sweet lego at least. Go check it out.

O’Reilly Ebook Pocket Reference Sale

(This is not a paid shill, I just really love the O’Reilly product.)

 
Share

Neither Patched Nor Unresolved

No Comments »

I’ve been playing with Devise for an authentication system for a project I’m working on (More on that when there’s something more solid), and I stumbled upon a heisenbug in omniauth-facebook, specifically in \lib\omniauth\facebook.rb, in the callback_url method:

def callback_url
        if @authorization_code_from_cookie
          ''
        else
          if options.authorize_options.respond_to?(:callback_url)
            options.authorize_options.callback_url
          else
            super
          end
        end
        #THIS LINE HERE IS IMPORTANT
      end

When I’d add ‘puts "callback_url finished"‘ in the commented line, the defect would go away (And leave me with another, but that’s another show). Remove the line, and it’d be back. Now, this is proof that the intelligence of the observer effects if they count AS an observer. A smarter man then me would have been able to collapse the defect’s waveform and figure out what was happening. Can you see it?

Read the rest of this entry

 
Share

What a difference an underscore makes

No Comments »

Ever get those errors which fill you with rage, swearing and spitting at your screen that The Fucking File’s right there. IT’S RIGHT THERE ARGHSFDFDSDFSF while the computer happily hums along, insisting it isn’t?

Yes, well, that was my morning, about a view, no less.

ActionView::MissingTemplate in Admin/dashboard#index

Showing --stuff-- line #1 raised:
Missing partial admin/dashboard/_job_summary with --stuff-- in view paths "C:/Projects/Qube/app/views"


I checked C:/Projects/Qube/app/views and found it contained /admin which contained /dashboard which contained /_job_summary.html.erb and I swore at my PC and thumped the desk and insulted Mats’ parentage.

All of which was dwarfed by cursing of supernaturally angry levels, when I discoved the stupid fucking brain-missing syntax-whining picky lousy error I’d made, which was to refer to the partial in the view using it as partial "_job_summary", in lieu of partial "job_summary".

See it? The _ which isn’t there in the second call to partial? That was it. Both totally obvious and completely missable, and wasted half an hour of my life. Well, I did, but the bloody underscore helped.

 
Share

WTF Am I doing, logging edition

No Comments »

My favorite stupid mistake is the kind you catch quickly and fix just as fast. Even when I make them. Like when I was logging today.

Yup. I can even screw up logging. I have a very special talent.

See, I was writing some logging for a daemon using The AMQP Gem and I want to mention when stuff is bound, that connections opened successfully, and so on. This log will be mostly used for after-the-fact defect diagnosis. I went ahead and wrote some logging statements after events happen such as

"Queue Created: Raywood, durable => true"
"Queue Raywood subscribed to exchange with routing key Brisbane"

Those log lines accurately describe what’s happened just prior to that line. What’s the catch?

Those log lines only accurately describe what’s happened just prior to that line, for now, assuming no weirdness with libraries.

Sure, right now I’m setting the Raywood queue to be durable, but what if (for some reason) it could be created non-durable and that declaration didn’t throw an error? That could easily happen with a library bug, or even by design. I could also change the line and forget to change the log, with the same result.

Logging should always reflect reality.

The best way to ensure that is by directly interrogating objects you’re logging about for their properties, rather then relying on what you’ve asked to happen, happening.

"Queue Created: #{queue.name}, durable => #{queue.opts.durable}"

If it’s optional for an operation to succeed, the logging should be tailored to reflect that possibility.

"Queue #{queue.name} subscribed to Exchange #{exchange.name} #{queue.subscribed? ? "succeeded" : "failed"}
 
Share

Deep Breath. Now Center…

1 Comment »

Now, I’m sure when it was created, the entire block VS inline & “lets have different means of aligning shit” mustn’t have seemed like a terrible idea. After all, surely having different formatting paradigms is a GREAT idea! CONTEXT SENSITIVE SHORTCUTS FOR EVERYONE! Still, our chances of getting a new, easy, consistent format are precisely fuckall, and will remain there until I can force people to upgrade their PC and browser by fiat, including all the empire building fuckwit device browsers (Yes, Fapple and Windows Mobile Phone 9 Excel Ultra Slimline Fantastico included).

I don’t have the time or energy to work out aligning shit by first principles, by sucking up to Tim Berners-Lee (’cause he’s got his own shit to do, like riding the mighty moon-worm) or by trying to interpret 407 different crappy “How does I CSS” posts.

So I just refered to this one, which is well written, easy to understand, and is slightly patronizing, which makes me feel less bad for not knowing already, even if it is NEEDLESSLY COMPLEX MINUTIA.

Seriously, Go Check It Out.

 
Share

jQuery sortable serialize shenanigans – The Enparsening of underscored attributes

No Comments »

Since writing your own UI elements from scratch is for chumps, I’ve been using jQuery to construct our new booking systems.  Lots of shiny there, all the better to Web-2.0 your social media with, my dear.

*{vomits a little in his mouth}*

I have a sortable list where each li element has an attribute storing object data.  An AJAX lookup supplies the data from a 3rd party source, and there can be 1..n li elements.  Calling serialize on that list allows me to get the ids of the list objects in their currently sorted order:

>>> $("#waypoints").sortable("serialize")

"waypoints[]=5&waypoints[]=8"

That’s OK, but I want to access the json data, not the ids.  I could put that data in a javascript array and then simply re-order it (or post the ids and the data separately and use the controller to order them), and I also could gouge my eyeballs out with a rusty spoon.  Thankfully, according to the docs, I can pass a hash to serialize specifying which attribute to return:

>>> $("#waypoints").sortable("serialize" {attribute: "json_data"})

"{"des_id":"a","des_name":"r","fleet[]=id":"5"}&  "{"des_id":"a","des_name":"r","fleet[]=id":"8"}

…Well that’s not what we what.  That’s weird, and what the fuck is going on with that inserted []?  Hmm, perhaps the key parameter is being clobbered and needs to be set as well (thus specifying what the first part should be):

>>> $("#waypoints").sortable("serialize" {attribute: "json_data", key: "waypoints"})

"waypoints[]=id":"5"}&waypoints=name":"8" }"

Nope, still fucked.  And weirdly escaped now, also.  I could use expression to create my own parsing regex, but I also could gouge my eyes out with a rusty spoon.  Into the source code, then, to see what the hell’s going on.

 serialize is defined on line 3365 of my copy of jquery-ui.js, and has this snippet:

3365
3366
3367
3368
$(items).each(function() {
    var res = ($(o.item || this).attr(o.attribute || 'id') || '').match(o.expression || (/(.+)[-=_](.+)/));
    if(res) str.push((o.key || res[1]+'[]')+'='+(o.key && o.expression ? res[1] : res[2]));
});

Ah.  That explains why I was getting that inserted [] in the last part of each value, and also why I wasn’t getting the full thing when I changed the key.  When I don’t pass an expression in, it chunks up the value by discarding the first group, and using the second.  In this case, everything up to the last underscore is discarded and the key used is everything before the last underscore, with a [] appended.  

When I supplied a key, it simply discarded the entire first matched group and returned the second.

So now I can solve my problem.  To parse an attribute containing underscores (or – or =) with serialize, I simply need to provide the attribute name, the key and a catchall expression, say, (.+):

>>> $("#waypoints").sortable("serialize" {attribute: "json_data", key: "waypoints", expression: "(.+)"})

"waypoints[]={"des_id":"a","des_name":"r","fleet_id":"5"}&  "{"des_id":"a","des_name":"r","fleet_id":"8"}"
 
Share

I’m a Big Boy Now!

No Comments »

I’ve been using a gem called rails3-jquery-autocomplete to easily hook up AJAX autocomplete into my views.  It’s fairly easy to use if a bit muddily documented.  However, I’ve recently had cause to want to pre-filter my input before using it in a search, and it seems that’s not a feature that the library offers.

 

Well Now It Is!  Providing they accept my pull request, which is anything but certain.  I’d never used rr before (lovely mocking/stubbing framework, writes much more fluently in my humble and naturally correct opinion), or shoulda, and frankly probably made arse-awful code and will bring down judgemental wrath.  I’d appreciate pointers if there are any readers who are fluent in Ruby and can give critique, it’s one of the hazards of working Forever Alone that you don’t get much feedback.

*{Crickets}*

O…K, I’ll just show you a usage sample then.  Both of you.

ZimController < ActionController::Base

  def more_horror (term)
    "Horrible #{term}"
  end

  :autocomplete :punishment, :name, :term_filter => :more_horror
end

 

Now, whenever the user is selecting a torture from one of their extensive list (drowning, Christmas with relatives, ASP.Net, those espresso flavored Monster’s, thumbscrews), before the auto-complete does its thing to return a list of possibilities, “Horrible ” will be prefixed to the selection, thus ensuring maximum pain and torment.  Take thatDib!

(As a somewhat worrying aside, either WordPress or Opera knows the spelling for thumbscrews.  Quite off putting.)

 
Share

Visualisations

No Comments »

A few days ago, Collin Van Dyke asked via Twitter for visualization options for heirachical data, and some Googling lead me to the JavaScript InfoVis Toolkit.  Lots of neat visualizations there, I particularly like the Icicle for hierarchical summation data (Like drilling down into greater precision of wage ranges) and the sunbeam (Just for prettiness).

Hope some of you find it useful.

 
Share

Partial Properties Haet Annotations or All About MetaDataType

No Comments »

Somewhere along the line I decided to use SubSonic for my ORM.  It might have something to do with the sense of humor of the major contributing author, Rob Conery, or its flexibility, or perhaps it’s just that it talks to me like I like to be talked too, and many many ORMs don’t.  As for MVC’s Entity Framework… I’d just rather not.

So, I’m using SubSonic and I’ve got a wee bit of a problem.  Validation for MVC3 is powered by annotations, as is their wont.  Adding an annotation is a simple matter of placing it above the property definition, as well you know:

public class LookingGlass{

  [GetsJam("Tomorrow")]
  public LookingGlassCharacter Alice {get; set;}

  [Required]
  public string AllMadHere{get; set;}

}

So adding a validation is simply a matter of typing it in, and away you go.  Now, SubSonic uses T4 templates to generate model classes from the database and… Oh.  Every time we re-generate we’re going to have to re-add our validations.  Shit.  But wait!  SubSonic generates partial classes!  When two partial classes have different annotations, the annotations are stacked when compiled! …But only for the class definition, not properties.  Shit, again.

So now what?  Well, now we need to use the MetaDataTypeAttribute. This tells a class to use another classes’ members’ metadata as its own.  Where this gets useful is when you consider that you can roll custom classes to provide metadata on a partial.  Since partial class attributes are stacked, your metadata attributes are applied to members of the composite class once created. You can then provide the metadata needed in “stub” properties in your metadata provider class:

[MetadataType(typeof(LookingGlassMetadata))

partial class LookingGlass {}


partial class LookingGlassMetadata {

  [GetsJam("Tomorrow")]
  public LookingGlassCharacter Alice {get; set;}

  [Required]
  public string AllMadHere {get; set;}

}

So now you’ve got annotations which can applied to properties in partial classes, and will survive a re-generation of a partial from a template. Sure, there’s replication, but that’s something we’ll address next time.

Neat huh?

 
Share

Bad Razor, BAD!

1 Comment »

What is wrong with this guy’s tutorial?  No thoughts?  OK.

How about this guy?  (Who is possibly even more egregious.)

I’ll give you a hint.  Even ScottGu is doing it.  In fact, he’s kinda responsible.

CODE DOES NOT BELONG IN VIEWS WHAT IS WRONG WITH YOU PEOPLE?

*{Sigh}* It feels better to have that out there.

Code belongs in Controllers.  Constraint Code belongs in Models.  Views?  They’re meant to be templates, and just templates.  Code should be limited to conditionals and loops, but only where those loops might change their display formatting.

Helpers are where you’re supposed to put formatting functions and template manipulation code.  Helpers are also usually not just littered all over your damn templates because Hey, they’re View Related right?.  Wrong. Also, I hate you.  Sure, it’s up to the individual developers to follow MVC principles, but most people are sheep.  You’re just encouraging them to write shitty applications.

There are some cures.  If you put your helpers in your App_Code folder, they’re fairly self-contained (although the syntax is still disgusting).  You can declare them as extensions to HtmlHelper (Same link as before).  And, using Single File Generators you can turn them into reusable libraries (Thanks David Ebbo!)  Just please, please, don’t put this crap directly into your views.

 
Share