lib/brief/document.rb in brief-1.1.0 vs lib/brief/document.rb in brief-1.2.0
- old
+ new
@@ -1,40 +1,76 @@
module Brief
class Document
include Brief::Document::Rendering
include Brief::Document::FrontMatter
- attr_accessor :path, :content, :frontmatter
+ attr_accessor :path, :content, :frontmatter, :raw_content
def initialize(path, options={})
@path = Pathname(path)
@options = options
if self.path.exist?
- content
+ @raw_content = path.read
load_frontmatter
end
self.model_class.try(:models).try(:<<, to_model) unless model_instance_registered?
end
- def content
- @content ||= path.read
+ def data
+ frontmatter
end
+ def sections
+ mappings = model_class.section_mappings
+
+ @sections = {}.to_mash
+
+ mappings.each do |name, mapping|
+ fragment = css("section[data-heading='#{name}']").first
+ @sections[name.parameterize.downcase.underscore] = Brief::Document::Section.new(name, fragment, mapping)
+ end
+
+ @sections
+ end
+
+ # Shortcut for querying the rendered HTML by css selectors.
+ #
+ # This will allow for model data attributes to be pulled from the
+ # document contents.
+ #
+ # Returns a Nokogiri::HTML::Element
+ def css(*args, &block)
+ parser.send(:css, *args, &block)
+ end
+
+ # Returns a Nokogiri::HTML::Element
+ def at(*args, &block)
+ parser.send(:at, *args, &block)
+ end
+
def extract_content(*args)
options = args.extract_options!
- args = options[:args] if options.is_a?(Hash) && options.key?(:args)
+ args = options.delete(:args) if options.is_a?(Hash) && options.key?(:args)
case
- when args.length == 1 && args.first.is_a?(String)
- css(args.first).try(:text).to_s
+ when options.empty? && args.length == 1 && args.first.is_a?(String)
+ results = css(args.first)
+ results = results.first if results.length > 1 && args.first.match(/:first-of-type/)
+ results.try(:text).to_s
+ else
+ binding.pry
end
end
- def data
- frontmatter
+ def relative_path_identifier
+ if Brief.case
+ path.relative_path_from(Brief.case.root)
+ else
+ path.to_s
+ end
end
def extension
path.extname
end
@@ -58,16 +94,30 @@
def respond_to?(method)
super || data.respond_to?(method) || data.key?(method)
end
+ def structure
+ @structure_analyzer ||= Brief::Document::Structure.new(fragment, self.raw_content.lines.to_a)
+ end
+
+ def parser
+ @parser ||= begin
+ structure.prescan
+ structure.create_wrappers
+ end
+ end
+
+ def fragment
+ @fragment ||= Nokogiri::HTML.fragment(to_raw_html)
+ end
+
def method_missing(meth, *args, &block)
if data.respond_to?(meth)
data.send(meth, *args, &block)
else
super
end
end
-
end
end