doc.rb 2.2 KB

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