docstache 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 09dcc56ee2a672c326f0dfeca2286abff6020861
4
+ data.tar.gz: f557ff91695d6cbdd27adb2901c6a8b5bb564e7a
5
+ SHA512:
6
+ metadata.gz: abdc024d14d88019410b688cf5ce50de62154e97bace385d330eb5f79f43934abb2cb71c7dd1cb19024ee95edab4bb86c833abe9b9c81debeda17d2d5193bb19
7
+ data.tar.gz: 24723da702b5a4e15dd8434ce8d7ff7ffc02f6586f1a170480e4313b44256c39132de7ae7585569a70692e77bc9849ac0323029a3e805f2637842ffa633e8d6b
data/.gitignore ADDED
@@ -0,0 +1,5 @@
1
+ .DS_Store
2
+ spec/example_input/tmp
3
+ .idea/
4
+ *.gem
5
+ Gemfile.lock
data/Gemfile ADDED
@@ -0,0 +1,3 @@
1
+ source 'https://rubygems.org'
2
+
3
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,176 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
data/README.rdoc ADDED
@@ -0,0 +1,24 @@
1
+ = Turns a docx file template and a data set into a fully formed docx document
2
+ Inspired from [https://github.com/jawspeak/ruby-docx-templater] and [https://github.com/michaelfranzl/docx_converter], this takes a .docx file and uses it as a template to create a new docx, with your data
3
+
4
+ == Features
5
+
6
+ * All manipulation in memory (great if you have sensitive data)
7
+ * Global key/value substitutions by entering a `$KEY$` anywhere in the word document, with whatever formatting you want.
8
+ * Multi-row loops inside tables, also with whatever your formatting you wish. `#BEGIN_ROW:XYZ#`... `#END_ROW:XYZ#` see tests/example
9
+ * Allows for embedded loops through fully recursive parsing of the document
10
+
11
+ == Usage
12
+ * Create your docx "template" in Word
13
+ * Install rvm and bundler
14
+ * Run `bundle install`.
15
+ * Render new docx files from the template, ex: `ruby render_docx_template.rb`. Look for a rendered_*.docx file.
16
+ * Sample output with tests: `rake spec` (unit tests) `rake integration` (opens word)
17
+
18
+ __MS WORD is painful__ You will probably need to modify your docx document in word until such a time as all flags to replace are set properly within a single XML element. You can’t have Word’s split a string of characters across multiple xml elements in your template document.
19
+ Test the template and keep fixing it until the fields are all set properly.
20
+
21
+ I frequently use this workflow:
22
+ - Cut string to replace out to notepad
23
+ - Paste string back into MS Word
24
+ - Save Word Document
data/Rakefile ADDED
@@ -0,0 +1,7 @@
1
+ require 'rspec/core/rake_task'
2
+ require 'rubocop/rake_task'
3
+
4
+ RSpec::Core::RakeTask.new(:spec)
5
+ RuboCop::RakeTask.new
6
+
7
+ task default: [:spec, :rubocop]
data/docstache.gemspec ADDED
@@ -0,0 +1,22 @@
1
+ # -*- encoding: utf-8 -*-
2
+ $:.push File.expand_path("../lib", __FILE__)
3
+ require "docstache/version"
4
+
5
+ Gem::Specification.new do |s|
6
+ s.name = "docstache"
7
+ s.version = Docstache::VERSION
8
+ s.authors = ["Will Cosgrove"]
9
+ s.email = ["will@willcosgrove.com"]
10
+ s.homepage = "https://github.com/willcosgrove/docstache"
11
+ s.summary = %q{Merges Hash of Data into Word docx template files using mustache syntax}
12
+ s.description = %q{Integrates data into MS Word docx template files. Processing supports loops and replacement of strings of data both outside and within loops.}
13
+ s.license = 'MIT'
14
+
15
+ s.files = `git ls-files`.split("\n")
16
+ s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
17
+ s.require_paths = ["lib"]
18
+
19
+ # specify any dependencies here; for example:
20
+ s.add_runtime_dependency 'nokogiri', '~> 1.6'
21
+ s.add_runtime_dependency 'rubyzip', '~> 1.1'
22
+ end
@@ -0,0 +1,102 @@
1
+ module Docstache
2
+ class Document
3
+ def initialize(*paths)
4
+ raise ArgumentError if paths.empty?
5
+ @path = paths.shift
6
+ @zip_file = Zip::File.open(@path)
7
+ @document = Nokogiri::XML(unzip_read(@zip_file, "word/document.xml"))
8
+ zip_files = paths.map{|p| Zip::File.open(p)}
9
+ documents = zip_files.map{|f| Nokogiri::XML(unzip_read(f, "word/document.xml"))}
10
+ documents.each do |doc|
11
+ @document.at_css('w|p:last').add_next_sibling(page_break)
12
+ @document.at_css('w|p:last').add_next_sibling(doc.at_css('w|body').children)
13
+ end
14
+ end
15
+
16
+ def tags
17
+ @document.text.gsub(/\s+/, '').scan(/\{\{[\w\.\/\#]+\}\}/)
18
+ end
19
+
20
+ def usable_tags
21
+ @document.css('w|t').select { |tag| tag.text =~ /\{\{[\w\.\/\#]+\}\}/ }.map(&:text)
22
+ end
23
+
24
+ def fix_errors
25
+ missing_tags = tags - usable_tags
26
+ problem_paragraphs = missing_tags.map { |tag|
27
+ @document.css('w|p').select {|t| t.text =~ /#{tag}/}.first
28
+ }
29
+
30
+ problem_paragraphs.each do |p|
31
+ flatten_paragraph(p) if p
32
+ end
33
+ end
34
+
35
+ def errors?
36
+ tags.length != usable_tags.length
37
+ end
38
+
39
+ def save
40
+ buffer = zip_buffer(@document)
41
+ File.open(@path, "w") {|f| f.write buffer.string}
42
+ end
43
+
44
+ def render_file(output, data={})
45
+ rendered = Docstache::Renderer.new(@document, data).render
46
+ buffer = zip_buffer(rendered)
47
+ File.open(output, "w") {|f| f.write buffer.string}
48
+ end
49
+
50
+ def render_stream(data={})
51
+ rendered = Docstache::Renderer.new(@document, data).render
52
+ buffer = zip_buffer(rendered)
53
+ buffer.rewind
54
+ return buffer.sysread
55
+ end
56
+
57
+ private
58
+
59
+ def flatten_paragraph(p)
60
+ runs = p.css('w|r')
61
+ host_run = runs.shift
62
+ runs.each do |run|
63
+ host_run.at_css('w|t').content += run.text
64
+ run.unlink
65
+ end
66
+ end
67
+
68
+ def unzip_read(zip, zip_path)
69
+ file = zip.find_entry(zip_path)
70
+ contents = ""
71
+ file.get_input_stream do |f|
72
+ contents = f.read
73
+ end
74
+ return contents
75
+ end
76
+
77
+ def zip_buffer(document)
78
+ buffer = Zip::OutputStream.write_buffer do |out|
79
+ @zip_file.entries.each do |e|
80
+ unless ["word/document.xml"].include?(e.name)
81
+ out.put_next_entry(e.name)
82
+ out.write(e.get_input_stream.read)
83
+ end
84
+ end
85
+ out.put_next_entry("word/document.xml")
86
+ out.write(@document.to_xml(indent: 0).gsub("\n", ""))
87
+ end
88
+ return buffer
89
+ end
90
+
91
+ def page_break
92
+ p = Nokogiri::XML::Node.new("p", @document)
93
+ p.namespace = @document.at_css('w|p:last').namespace
94
+ r = Nokogiri::XML::Node.new("r", @document)
95
+ p.add_child(r)
96
+ br = Nokogiri::XML::Node.new("br", @document)
97
+ r.add_child(br)
98
+ br['w:type'] = "page"
99
+ return p
100
+ end
101
+ end
102
+ end
@@ -0,0 +1,152 @@
1
+ module Docstache
2
+ class Renderer
3
+ def initialize(xml, data)
4
+ @content = xml
5
+ @data = data
6
+ end
7
+
8
+ def render
9
+ process_content
10
+ return @content
11
+ end
12
+
13
+ private
14
+
15
+ def process_content
16
+ parse_content(@content.elements)
17
+
18
+ content_tr = @content.xpath('//w:tr')
19
+
20
+ cleanup_loop(content_tr)
21
+ end
22
+
23
+ def extract_end_row(nd, key)
24
+ if !nd.nil?
25
+ case nd.text.to_s
26
+ when /\{\{\/#{key.to_s}\}\}/
27
+ puts "Found End Row for #{key.to_s}"
28
+ return nd
29
+ else
30
+ return extract_end_row(nd.next, key)
31
+ end
32
+ else
33
+ return nil
34
+ end
35
+ end
36
+
37
+ def expand_loop(nd, end_nd, key, element)
38
+ out = []
39
+ case nd.text.to_s
40
+ when /\{\{\##{key.to_s}\}\}/
41
+ out = expand_loop(nd.next, end_nd, key, element)
42
+ when end_nd.text.to_s
43
+ out = []
44
+ when /\{\{\#([a-zA-Z0-9_\.]+)\}\}/
45
+ new_key = $1.to_sym
46
+ out += process_loop(nd, new_key, element)
47
+ else
48
+ new_node = nd.dup
49
+ puts "Adding Row #{nd.text} to list"
50
+ parse_content(new_node.elements, element)
51
+ out << new_node
52
+ puts "Next Node is: #{nd.next.text.to_s}"
53
+ out += expand_loop(nd.next, end_nd, key, element)
54
+ end
55
+ return out
56
+ end
57
+
58
+
59
+ def remove_loop(nd, key)
60
+ if nd
61
+ case nd.text.to_s
62
+ when /\{\{\/#{key.upcase.to_s}\}\}/
63
+ nd.unlink
64
+ else
65
+ remove_loop(nd.next, key)
66
+ nd.unlink
67
+ end
68
+ end
69
+ end
70
+
71
+
72
+ def process_loop(nd, key, data)
73
+ out = []
74
+ puts "Found Loop #{key.to_s}"
75
+ end_row = extract_end_row(nd, key)
76
+
77
+ if !data.has_key?(key)
78
+ nil # Error in the data model
79
+ return []
80
+ elsif data[key].empty?
81
+ remove_loop(nd, key) # No data to put in
82
+ return []
83
+ else # Actual loop to process
84
+ data_set = data[key]
85
+ puts "Expanding Rows for loop #{key.to_s}"
86
+ puts "Data count is #{data_set.count}"
87
+ puts "Data is #{data_set}"
88
+
89
+ data_set.each do |element|
90
+ out += expand_loop(nd, end_row, key, element)
91
+ end
92
+ return out
93
+ end
94
+ end
95
+
96
+ def parse_content(elements, data=@data)
97
+ elements.each do |nd|
98
+ case nd.name
99
+ when "tr"
100
+ case nd.text.to_s
101
+ when /\{\{\#([a-zA-Z0-9_\.]+)\}\}/
102
+ key = $1.to_sym
103
+ # Get elements to add
104
+ elements = process_loop(nd, key, data)
105
+ # Add elements
106
+ elements.reverse.each do |e|
107
+ puts "Adding Row to file: #{e.text.to_s}"
108
+ nd.add_next_sibling(e)
109
+ end
110
+ else # it's a normal table row
111
+ parse_content(nd.elements, data)
112
+ end
113
+ when "t" # It's a leaf that contains data to replace
114
+ subst_content(nd, data)
115
+ else # it's neither a leaf or a loop so let's process it
116
+ parse_content(nd.elements, data)
117
+ end
118
+ end
119
+ end
120
+
121
+ def cleanup_loop(nodeset) # Acts in w/tr only as loops are based on these
122
+ nodeset.each do |nd|
123
+ case nd.text.to_s
124
+ when /\{\{\#([a-zA-Z0-9_\.]+)\}\}/
125
+ nd.unlink
126
+ when /\{\{\/([a-zA-Z0-9_\.]+)\}\}/
127
+ nd.unlink
128
+ when /\{\{[a-zA-Z0-9_\.]+\}\}/
129
+ nd.unlink
130
+ end
131
+ end
132
+ end
133
+
134
+ def subst_content(nd, data)
135
+ inner = nd.inner_html
136
+ keys = nd.text.scan(/\{\{([a-zA-Z0-9_\.]+)\}\}/).map(&:first).map(&:to_sym)
137
+ keys.each do |key|
138
+ value = data[key]
139
+ puts "Substituting {{#{key.to_s}}} with #{value}"
140
+ inner.gsub!("{{#{key.to_s}}}", safe(value))
141
+ end
142
+ if !keys.empty?
143
+ nd.inner_html = inner
144
+ end
145
+ end
146
+
147
+ def safe(text)
148
+ text.to_s
149
+ end
150
+
151
+ end
152
+ end
@@ -0,0 +1,3 @@
1
+ module Docstache
2
+ VERSION = "0.0.1"
3
+ end
data/lib/docstache.rb ADDED
@@ -0,0 +1,9 @@
1
+ require 'nokogiri'
2
+ require 'zip'
3
+
4
+ require "docstache/renderer"
5
+ require "docstache/document"
6
+
7
+ module Docstache
8
+ #noop
9
+ end