doc.rb 1.8 KB

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