doc.rb 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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)) && page[:entries].present?
  30. yield page[:store_path], page[:output]
  31. index = EntryIndex.new
  32. index.add page[:entries]
  33. index
  34. end
  35. end
  36. def index_pages
  37. index = EntryIndex.new
  38. new.build_pages do |page|
  39. next if page[:entries].blank?
  40. yield page[:store_path], page[:output]
  41. index.add page[:entries]
  42. end
  43. index.empty? ? nil : index
  44. end
  45. def store_page(store, id)
  46. store.open path do
  47. index = index_page(id, &store.method(:write))
  48. !!index
  49. end
  50. end
  51. def store_pages(store)
  52. store.replace path do
  53. index = index_pages(&store.method(:write))
  54. store.write INDEX_FILENAME, index.to_json if index
  55. !!index
  56. end
  57. end
  58. end
  59. def initialize
  60. raise NotImplementedError, "#{self.class} is an abstract class and cannot be instantiated." if self.class.abstract
  61. end
  62. def build_page(id, &block)
  63. raise NotImplementedError
  64. end
  65. def build_pages(&block)
  66. raise NotImplementedError
  67. end
  68. end
  69. end