Topic: When & Where to sort_by?

I think I am missing something fundamental here. I am fooling around with couchDB and I ask it for a chapter of Scripture - e.g. Acts_1. Examining the raw record, the verses are stored as a hash (.e.g. {"1" => "In my former book, ...", etc.}) and the key is a string (and there are reasons for that, don't ask<G>). Anyway, when I get the record the hash (scripture.verses) appears in random order. OK, maybe it really is in random order and the couchDB utility program sorts the hash, but I doubt it, so lets say the verses are in correct order in the DB.

First question: Why does the hash appear in random order in the RoR code? Where is it getting randomized?

I suppose I should'ought'a not presume an order when I pull a record from the DB - who knows who has been doing what in there - right? So when I display the verses I do this (using haml) ...
    - @scripture.verses.sort_by {|k,v| k.to_i}.each do |key,verse|
      %span{:style => "vertical-align: super; font-size: small;"} # I'll get around to putting it in the style sheet
        = key
      = verse
And it works just fine. But shouldn't I be doing the sort in the model? I redefined "find" in the model so it calls it's super class to get the record, then I sort and pass the record on thusly...
  def find( current_db, id)
    scripture = Scripture.super.find( current_db, id)
    scripture.verses = scripture.verses.sort_by {|k,v| k.to_i}
    scripture
  end
Which doesn't fail, but when I get to the view - the cockamamie hash is back in random order! Arrrrggggg!

Second question: What am I missing here?

thanks for your help
grace and peace
Paul+

Why prayer when you can fret and worry?

Re: When & Where to sort_by?

Wish I could help you - I have no experience with CouchDB. I can tell you that usually sorting Ruby objects is an order of magnitude slower than pulling them out of the database in the right order.

Ryan Heneise  |  Art of Mission  |  Now with extra-strong Donor Tools mojo

Re: When & Where to sort_by?

AMEN!!! to getting the stuff out of the DB in the right order! Even so, since the original post I have learned that couchDB does not guarantee order of fields or elements in hashes. And I had a duh-BGO - the ROR interface to couchDB I am using is not ActiveRecord thus most of the callbacks are not predefined - so, of course, my sort didn't fire when I expected it to (duh**2).

Having said all that, I like fooling around with couchDB. I like the way it handles text. But it's probably not quite ready for prime time - at least at my skill level.

grace and peace

Why prayer when you can fret and worry?

Re: When & Where to sort_by?

I JUST learned that as of Ruby 1.9 hash order will be preserved. Prior to 1.9, no guarantees.

Why prayer when you can fret and worry?