1
0

entry_index.rb 1001 B

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