doc.rb 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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 store_page(store, id)
  29. store.open(path) do
  30. if page = new.build_page(id) and store_page?(page)
  31. store.write page[:store_path], page[:output]
  32. true
  33. else
  34. false
  35. end
  36. end
  37. end
  38. def index_pages
  39. index = EntryIndex.new
  40. new.build_pages do |page|
  41. next if page[:entries].blank?
  42. yield page[:store_path], page[:output]
  43. index.add page[:entries]
  44. end
  45. index.empty? ? nil : index
  46. end
  47. def store_pages(store)
  48. store.replace path do
  49. index = index_pages(&store.method(:write))
  50. store.write INDEX_FILENAME, index.to_json if index
  51. !!index
  52. end
  53. end
  54. private
  55. def store_page?(page)
  56. page[:entries].present?
  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