entry_index.rb 888 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. require 'yajl/json_gem'
  2. module Docs
  3. class EntryIndex
  4. attr_reader :entries, :types
  5. def initialize
  6. @entries = []
  7. @types = Hash.new { |hash, key| hash[key] = Type.new key }
  8. end
  9. def add(entry)
  10. if entry.is_a? Array
  11. entry.each(&method(:add))
  12. else
  13. add_entry(entry) unless entry.root?
  14. end
  15. end
  16. def empty?
  17. @entries.empty?
  18. end
  19. def length
  20. @entries.length
  21. end
  22. def as_json
  23. { entries: entries_as_json, types: types_as_json }
  24. end
  25. def to_json
  26. JSON.generate(as_json)
  27. end
  28. private
  29. def add_entry(entry)
  30. @entries << entry.dup
  31. @types[entry.type].count += 1 if entry.type
  32. end
  33. def entries_as_json
  34. @entries.sort!.map { |entry| entry.as_json }
  35. end
  36. def types_as_json
  37. @types.values.sort!.map { |type| type.as_json }
  38. end
  39. end
  40. end