History

Created Filter Reference (markdown)

Thibaut Courouble committed 13 years ago

Commit 91ef8e71 parent 6f3be071 file · +222 −0Browse files

Unified · Split

Filter-Reference.md+222−0
@@ -0,0 +1,222 @@
1---
2
3**Table of contents:**
4
5* [Overview](https://github.com/Thibaut/devdocs/wiki/Filter-Reference#overview)
6* [Instance methods](https://github.com/Thibaut/devdocs/wiki/Filter-Reference#instance-methods)
7* [Core filters](https://github.com/Thibaut/devdocs/wiki/Filter-Reference#core-filters)
8* [Custom filters](https://github.com/Thibaut/devdocs/wiki/Filter-Reference#custom-filters)
9 - [CleanHtmlFilter](https://github.com/Thibaut/devdocs/wiki/Filter-Reference#cleanhtmlfilter)
10 - [EntriesFilter](https://github.com/Thibaut/devdocs/wiki/Filter-Reference#entriesfilter)
11
12## Overview
13
14Filters use the [HTML::Pipeline](https://github.com/jch/html-pipeline) library. They take an HTML string or [Nokogiri](http://nokogiri.org/) node as input, optionally perform modifications and/or extract information from it, and then outputs the result. Together they form a pipeline where each filter hands its output to the next filter's input. Every documentation page passes through this pipeline before being copied on the local filesystem.
15
16Filters are subclasses of the [`Docs::Filter`](https://github.com/Thibaut/devdocs/blob/master/lib/docs/core/filter.rb) class and require a `call` method. A basic implementation looks like this:
17
18```ruby
19module Docs
20 class CustomFilter < Filter
21 def call
22 doc
23 end
24 end
25end
26```
27
28Filters which manipulate the Nokogiri node object (`doc` and related methods) are _HTML filters_ and must not manipulate the HTML string (`html`). Vice-versa, filters which manipulate the string representation of the document are _text filters_ and must not manipulate the Nokogiri node object. The two types are divided into two stacks within the scrapers. These stacks are then combined into a pipeline that calls the HTML filters before the text filters (more details [here](https://github.com/Thibaut/devdocs/wiki/Scraper-Reference#filter-stacks)). This is to avoid parsing the document multiple times.
29
30The `call` method must return either `doc` or `html`, depending on the type of filter.
31
32## Instance methods
33
34* `doc` [Nokogiri::XML::Node]
35 The Nokogiri representation of the container element.
36 See [Nokogiri's API docs](http://nokogiri.org/Nokogiri/XML/Node.html#methods_nav) for the list of available methods.
37
38* `html` [String]
39 The string representation of the container element.
40
41* `context` [Hash] **(frozen)**
42 The scraper's `options` along with a few additional keys: `:base_url`, `:root_url`, `:root_page` and `:url`.
43
44* `result` [Hash]
45 Used to store the page's metadata and pass back information to the scraper.
46 Possible keys:
47
48 - `:path` — the page's normalized path
49 - `:store_path` — the path where the page will be stored (equal to `:path` with `.html` at the end)
50 - `:internal_urls` — the list of distinct internal URLs found within the page
51 - `:entries` — the [`Entry`](https://github.com/Thibaut/devdocs/blob/master/lib/docs/core/models/entry.rb) objects to add to the index
52
53* `css`, `at_css`, `xpath`, `at_xpath`
54 Shortcuts for `doc.css`, `doc.xpath`, etc.
55
56* `base_url`, `current_url`, `root_url` [Docs::URL]
57 Shortcuts for `context[:base_url]`, `context[:url]`, and `context[:root_url]` respectively.
58
59* `root_path` [String]
60 Shortcut for `context[:root_path]`.
61
62* `subpath` [String]
63 The sub-path from the base URL of the current URL.
64 _Example: if `base_url` equals `example.com/docs` and `current_url` equals `example.com/docs/file?raw`, the returned value is `/file`._
65
66* `slug` [String]
67 The `subpath` removed of any leading slash or `.html` extension.
68 _Example: if `subpath` equals `/dir/file.html`, the returned value is `dir/file`._
69
70* `root_page?` [Boolean]
71 Returns `true` if the current page is the root page.
72
73## Core filters
74
75* [`ContainerFilter`](https://github.com/Thibaut/devdocs/blob/master/lib/docs/filters/core/container.rb) — changes the root node of the document (remove everything outside)
76* [`CleanHtmlFilter`](https://github.com/Thibaut/devdocs/blob/master/lib/docs/filters/core/clean_html.rb) — removes HTML comments, `<script>`, `<style>`, etc.
77* [`NormalizeUrlsFilter`](https://github.com/Thibaut/devdocs/blob/master/lib/docs/filters/core/normalize_urls.rb) — replaces all URLs with their fully qualified counterpart
78* [`InternalUrlsFilter`](https://github.com/Thibaut/devdocs/blob/master/lib/docs/filters/core/internal_urls.rb) — detects internal URLs (the ones to scrape) and replaces them with their unqualified, relative counterpart
79* [`NormalizePathsFilter`](https://github.com/Thibaut/devdocs/blob/master/lib/docs/filters/core/normalize_paths.rb) — makes the internal paths consistent (e.g. always end with `.html`)
80* [`InnerHtmlFilter`](https://github.com/Thibaut/devdocs/blob/master/lib/docs/filters/core/inner_html.rb) — converts the document to a string
81* [`CleanTextFilter`](https://github.com/Thibaut/devdocs/blob/master/lib/docs/filters/core/clean_text.rb) — removes empty nodes
82* [`AttributionFilter`](https://github.com/Thibaut/devdocs/blob/master/lib/docs/filters/core/attribution.rb) — appends the license info and link to the original document
83* [`TitleFilter`](https://github.com/Thibaut/devdocs/blob/master/lib/docs/filters/core/title.rb) — prepends the document with a title (disabled by default)
84* [`EntriesFilter`](https://github.com/Thibaut/devdocs/blob/master/lib/docs/filters/core/entries.rb) — abstract filter for extracting the page's metadata
85
86## Custom filters
87
88Scrapers can have any number of custom filters but require at least the two described below.
89
90**Note:** filters are located in the [`lib/docs/filters`](https://github.com/Thibaut/devdocs/tree/master/lib/docs/filters/) directory. The class's name must be the [CamelCase](http://api.rubyonrails.org/classes/String.html#method-i-camelize) equivalent of the filename.
91
92### `CleanHtmlFilter`
93
94The `CleanHtml` filter is tasked with cleaning the HTML markup where necessary and removing anything superfluous or nonessential. Only the core documentation should remain at the end.
95
96Nokogiri's many jQuery-like methods make it easy to search and modify elements — see the [API docs](http://nokogiri.org/Nokogiri/XML/Node.html#methods_nav).
97
98Here's an example implementation that covers the most common use-cases:
99
100```ruby
101module Docs
102 class MyScraper
103 class CleanHtmlFilter < Filter
104 def call
105 css('hr').remove
106 css('#changelog').remove if root_page?
107
108 # Set id attributes on <h3> instead of an empty <a>
109 css('h3').each do |node|
110 node['id'] = node.at_css('a')['id']
111 end
112
113 # Make proper table headers
114 css('td.header').each do |node|
115 node.name = 'th'
116 end
117
118 # Remove code highlighting
119 css('pre').each do |node|
120 node.content = node.content
121 end
122
123 doc
124 end
125 end
126 end
127end
128```
129
130**Notes:**
131
132* Empty elements will be automatically removed by the core `CleanTextFilter` later in the pipeline's execution.
133* Although the goal is to end up with a clean version of the page, try to keep the number of modifications to a minimum, so as to make the code easier to maintain. Custom CSS is the preferred way of normalizing the pages (except for hiding stuff which should always be done by removing the markup).
134* Try to document your filter's behavior as much as possible, particularly modifications that apply only to a subset of pages. It'll make updating the documentation easier.
135
136### `EntriesFilter`
137
138The `Entries` filter is responsible for extracting the page's metadata, represented by a set of _entries_, each with a name, type and path.
139
140The following two models are used under the hood to represent the metadata:
141
142* [`Entry(name, type, path)`](https://github.com/Thibaut/devdocs/blob/master/lib/docs/core/models/entry.rb)
143* [`Type(name, slug, count)`](https://github.com/Thibaut/devdocs/blob/master/lib/docs/core/models/type.rb)
144
145Each scraper must implement its own `EntriesFilter` by subclassing the [`Docs::EntriesFilter`](https://github.com/Thibaut/devdocs/blob/master/lib/docs/filters/core/entries.rb) class. The base class already implements the `call` method and includes four methods which the subclasses can override:
146
147* `get_name` [String]
148 The name of the default entry (aka. the page's name).
149 It is usually guessed from the `slug` (documented above) or by searching the HTML markup.
150 **Default:** modified version of `slug` (underscores are replaced with spaces and forward slashes with dots)
151
152* `get_type` [String]
153 The type of the default entry (aka. the page's type).
154 Entries without a type can be searched for but won't be listed in the app's sidebar (unless no other entries have a type).
155 **Default:** `nil`
156
157* `include_default_entry?` [Boolean]
158 Whether to include the default entry.
159 Used when a page consists of multiple entries (returned by `additional_entries`) but doesn't have a name/type of its own, or to remove a page from the index (if it has no additional entries), in which case it won't be copied on the local filesystem and any link to it in the other pages will be broken (as explained on the [Scraper Reference](https://github.com/Thibaut/devdocs/wiki/Scraper-Reference) page, this is used to keep the `:skip` / `:skip_patterns` options to a maintainable size, or if the page includes links that can't reached from anywhere else).
160 **Default:** `true`
161
162* `additional_entries` [Array]
163 The list of additional entries.
164 Each entry is represented by an Array of three attributes: its name, fragment identifier, and type. The fragment identifier refers to the `id` attribute of the HTML element (usually a heading) that the entry relates to. It is combined with the page's path to become the entry's path. If absent or `nil`, the page's path is used. If the type is absent or `nil`, the default `type` is used.
165 Example: `[ ['One'], ['Two', 'id'], ['Three', nil, 'type'] ]` adds three additional entries, the first one named "One" with the default path and type, the second one named "Two" with the URL fragment "#id" and the default type, and the third one named "Three" with the default path and the type "type".
166 The list is usually constructed by running through the markup. Exceptions can also be hard-coded for specific pages.
167 **Default:** `[]`
168
169The following accessors are also available, but must not be overridden:
170
171* `name` [String]
172 Memoized version of `get_name` (`nil` for the root page).
173
174* `type` [String]
175 Memoized version of `get_type` (`nil` for the root page).
176
177**Notes:**
178
179* Leading and trailing whitespace is automatically removed from names and types.
180* Names must be unique across the documentation and as short as possible (ideally less than 30 characters). Whenever possible, methods should be differentiated from properties by appending `()`, and instance methods should be differentiated from class methods using the `Class#method` or `object.method` conventions.
181* You can call `name` from `get_type` or `type` from `get_name` but doing both will cause a stack overflow (i.e. you can infer the name from the type or the type from the name, but you can't do both at the same time). Don't call `get_name` or `get_type` directly as their value isn't memoized.
182* The root page has no name and no type (both are `nil`). `get_name` and `get_type` won't get called with the page (but `additional_entries` will).
183* `Docs::EntriesFilter` is an _HTML filter_. It must be added to the scraper's `html_filters` stack.
184* Try to document the code as much as possible, particularly the special cases. It'll make updating the documentation easier.
185
186**Example:**
187
188```ruby
189module Docs
190 class MyScraper
191 class EntriesFilter < Docs::EntriesFilter
192 def get_name
193 node = at_css('h1')
194 result = node.content.strip
195 result << ' event' if type == 'Events'
196 result << '()' if node['class'].try(:include?, 'function')
197 result
198 end
199
200 def get_type
201 object, method = *slug.split('/')
202 method ? object : 'Miscellaneous'
203 end
204
205 def additional_entries
206 return [] if root_page?
207
208 css('h2').map do |node|
209 [node.content, node['id']]
210 end
211 end
212
213 def include_default_entry?
214 !at_css('.obsolete')
215 end
216 end
217 end
218end
219```
220
221---
222_Feel free to edit this page or ask for improvements on the [mailing list](https://groups.google.com/d/forum/devdocs)._