entry_index.rb 923 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. alias_method :blank?, :empty?
  20. def length
  21. @entries.length
  22. end
  23. def as_json
  24. { entries: entries_as_json, types: types_as_json }
  25. end
  26. def to_json
  27. JSON.generate(as_json)
  28. end
  29. private
  30. def add_entry(entry)
  31. @entries << entry.dup
  32. @types[entry.type].count += 1 if entry.type
  33. end
  34. def entries_as_json
  35. @entries.sort!.map { |entry| entry.as_json }
  36. end
  37. def types_as_json
  38. @types.values.sort!.map { |type| type.as_json }
  39. end
  40. end
  41. end