Search code examples
rubymiddleman

Middleman blog - custom sorting


I'm interested in using middleman as a site to organize online lessons therefore I'd like to modify the way middleman's blog system sorts blog posts by date. I'd like to make it sort by chapter number and lesson number.

So instead of placing latest post first it would place Chapter 1 - Lesson 1 first, etc. I can currently do this in a hacky way by reversing the order of dates for each post.

Is there a simple way to modify it's post sorting method? If not, is there a way to override this somewhere like a Rail's initializer file?

Thanks!


Solution

    1. Make chapter and lesson numbers available via Frontmatter.
    2. Use Ruby's sort_by ability of accepting an array of fields to sort with.

    Here's some code for you to understand what i mean:

    pages = [
      {
        chapter: 2,
        lesson:  1
      },
      {
        chapter: 1,
        lesson:  2
      },
      {
        chapter: 2,
        lesson:  2
      },
      {
        chapter: 1,
        lesson:  1
      }  
    ]
    
    pages.sort_by { |page|
      [
        page[:chapter], 
        page[:lesson]
      ]
    }
    
    # => [
    #      {"chapter"=>1, "lesson"=>1},
    #      {"chapter"=>1, "lesson"=>2},
    #      {"chapter"=>2, "lesson"=>1},
    #      {"chapter"=>2, "lesson"=>2}
    #    ] 
    

    Live demo: http://rubyfiddle.com/riddles/29e55