doc.rb 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. module Docs
  2. class Doc
  3. INDEX_FILENAME = 'index.json'
  4. class << self
  5. attr_accessor :name, :slug, :type, :version, :abstract
  6. def inherited(subclass)
  7. subclass.type = type
  8. end
  9. def name
  10. @name || super.try(:demodulize)
  11. end
  12. def slug
  13. @slug || name.try(:downcase)
  14. end
  15. def path
  16. slug
  17. end
  18. def index_path
  19. File.join path, INDEX_FILENAME
  20. end
  21. def as_json
  22. { name: name,
  23. slug: slug,
  24. type: type,
  25. version: version,
  26. index_path: index_path }
  27. end
  28. def index_page(id)
  29. if page = new.build_page(id)
  30. yield page[:store_path], page[:output]
  31. index = EntryIndex.new
  32. index.add page[:entries]
  33. end
  34. index
  35. end
  36. def index_pages
  37. index = EntryIndex.new
  38. new.build_pages do |page|
  39. yield page[:store_path], page[:output]
  40. index.add page[:entries]
  41. end
  42. index.empty? ? nil : index
  43. end
  44. def store_page(store, id)
  45. store.open path do
  46. index = index_page(id, &store.method(:write))
  47. !!index
  48. end
  49. end
  50. def store_pages(store)
  51. store.replace path do
  52. index = index_pages(&store.method(:write))
  53. store.write INDEX_FILENAME, index.to_json if index
  54. !!index
  55. end
  56. end
  57. end
  58. def initialize
  59. raise NotImplementedError, "#{self.class} is an abstract class and cannot be instantiated." if self.class.abstract
  60. end
  61. def build_page(id, &block)
  62. raise NotImplementedError
  63. end
  64. def build_pages(&block)
  65. raise NotImplementedError
  66. end
  67. end
  68. end