Sha256: d42d54a8aa62896c8073f7cf37c723b9f2d8708de3732d7237acb23141bb7fb5

Contents?: true

Size: 1.34 KB

Versions: 3

Compression:

Stored size: 1.34 KB

Contents

module CSL
  
  class Sort < Node
    attr_children 'key'

    alias :keys :key
    
    def sort(items, processor)
      items.sort do |a,b|
        comparison = 0
        keys.each do |key|
          this, that = key.convert(a, processor), key.convert(b, processor)

          # Duplicate Ruby 1.9's <=> behavior for nil
          if this.nil? && that.nil?
            comparison = 0
          elsif this.nil? || that.nil?
            comparison = nil
          else
            comparison = this <=> that
          end
          
          comparison = comparison * -1 if comparison && key.descending?

          comparison = comparison ? comparison : that.nil? ? -1 : 1
        
          break unless comparison.zero?
        end
        
        comparison
      end
    end
    
    alias :apply :sort
    
  end
  
  class Key < Node
    attr_fields %w{ variable macro sort names-min names-use-first names-use-last }
    
    def convert(item, processor)
      case
      when has_variable?
        item[variable]
      when has_macro?
        processor.style.macros[macro].process(item, processor)
      else
        CiteProc.log.warn "sort key #{ inspect } contains no variable or macro definition."
        item
      end
    end
    
    def ascending?; !descending?; end
    
    def descending?
      has_sort? && sort == 'descending'
    end
    
  end
  
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
citeproc-ruby-0.0.6 lib/csl/sort.rb
citeproc-ruby-0.0.5 lib/csl/sort.rb
citeproc-ruby-0.0.4 lib/csl/sort.rb