Sha256: 5037d355e15bc5cff30710b2b9c899688f749c069c085f9b17ff8499df97fafd

Contents?: true

Size: 1.11 KB

Versions: 5

Compression:

Stored size: 1.11 KB

Contents

module Trestle
  class Navigation
    extend ActiveSupport::Autoload

    autoload :Block
    autoload :Item
    autoload :Group
    autoload :NullGroup, "trestle/navigation/group"

    attr_reader :items

    def initialize(items)
      @items = items
    end

    def by_group
      sorted_groups = stable_sort(items.group_by { |item| groups[item.group.id] })
      sorted_items = sorted_groups.map { |group, items| [group, stable_sort(items)] }

      Hash[sorted_items]
    end

    def each(&block)
      by_group.each(&block)
    end

    def first
      sorted = by_group.values
      sorted.first.first if sorted.any?
    end

    def self.build(blocks, context)
      new(blocks.map { |block|
        block.items(context)
      }.flatten.select { |item|
        item.visible?(context)
      })
    end

  private
    def stable_sort(items)
      items.sort_by.with_index { |item, i| [item, i] }
    end

    def groups
      @groups ||= items.inject({}) { |groups, item|
        group = groups[item.group.id]

        groups[item.group.id] = group ? group.merge(item.group) : item.group
        groups
      }
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
trestle-0.9.2 lib/trestle/navigation.rb
trestle-0.9.1 lib/trestle/navigation.rb
trestle-0.9.0 lib/trestle/navigation.rb
trestle-0.8.13 lib/trestle/navigation.rb
trestle-0.8.12 lib/trestle/navigation.rb