oxml_maker 0.1.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
+ SHA256:
3
+ metadata.gz: 04e8ffba5e41ae76da239d31522428b1b0ea32f66f6ecf7cbf2a5c81c742a158
4
+ data.tar.gz: 44b680d0515bc4081474d741a90ef4e75bb1baac4140dc25f94e54d91d4fa94c
5
+ SHA512:
6
+ metadata.gz: e861ef91354f8eae531c3863fe24051e5083de602a3f4ba5968affe66c2c8b0f41c229cc6c1b987d7f1b07961827d29610d0ad23d82f175257b98c2f92a785d4
7
+ data.tar.gz: 565441a6e469752394a08bde5dd1baf50cb7d4bfc7e8d6d8f07fc9164f1f6354a6450fda223579421c961a9a67091f39578ad29595edd8a891abb877e0e0b494
data/.rubocop.yml ADDED
@@ -0,0 +1,9 @@
1
+ AllCops:
2
+ TargetRubyVersion: 3.1
3
+ NewCops: enable
4
+
5
+ Style/StringLiterals:
6
+ EnforcedStyle: double_quotes
7
+
8
+ Style/StringLiteralsInInterpolation:
9
+ EnforcedStyle: double_quotes
data/CHANGELOG.md ADDED
@@ -0,0 +1,26 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.1] - 2025-10-20
4
+
5
+ ### Added
6
+ - Rubyzip 3.2 support for DOCX generation
7
+ - Comprehensive test suite (63 tests, 274 assertions)
8
+ - Rails-optional architecture with smart public directory detection
9
+ - Full workflow integration tests
10
+ - ZIP functionality tests
11
+ - Complete documentation consolidation
12
+
13
+ ### Changed
14
+ - Updated rubyzip dependency from ~> 2.3 to ~> 3.2
15
+ - Improved method naming (`copy_zip_to_docx` → `convert_zip_to_docx`)
16
+ - Extracted section generation logic into separate method
17
+ - Consolidated TESTING.md and EXAMPLE.md into README.md
18
+
19
+ ### Fixed
20
+ - Missing ZIP-to-DOCX conversion step in Document#create
21
+ - Rubyzip 3.x API compatibility (removed deprecated CREATE constant)
22
+ - Rails dependency made optional with fallback support
23
+
24
+ ## [0.1.0] - 2025-06-09
25
+
26
+ - Initial release
@@ -0,0 +1,132 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our
6
+ community a harassment-free experience for everyone, regardless of age, body
7
+ size, visible or invisible disability, ethnicity, sex characteristics, gender
8
+ identity and expression, level of experience, education, socio-economic status,
9
+ nationality, personal appearance, race, caste, color, religion, or sexual
10
+ identity and orientation.
11
+
12
+ We pledge to act and interact in ways that contribute to an open, welcoming,
13
+ diverse, inclusive, and healthy community.
14
+
15
+ ## Our Standards
16
+
17
+ Examples of behavior that contributes to a positive environment for our
18
+ community include:
19
+
20
+ * Demonstrating empathy and kindness toward other people
21
+ * Being respectful of differing opinions, viewpoints, and experiences
22
+ * Giving and gracefully accepting constructive feedback
23
+ * Accepting responsibility and apologizing to those affected by our mistakes,
24
+ and learning from the experience
25
+ * Focusing on what is best not just for us as individuals, but for the overall
26
+ community
27
+
28
+ Examples of unacceptable behavior include:
29
+
30
+ * The use of sexualized language or imagery, and sexual attention or advances of
31
+ any kind
32
+ * Trolling, insulting or derogatory comments, and personal or political attacks
33
+ * Public or private harassment
34
+ * Publishing others' private information, such as a physical or email address,
35
+ without their explicit permission
36
+ * Other conduct which could reasonably be considered inappropriate in a
37
+ professional setting
38
+
39
+ ## Enforcement Responsibilities
40
+
41
+ Community leaders are responsible for clarifying and enforcing our standards of
42
+ acceptable behavior and will take appropriate and fair corrective action in
43
+ response to any behavior that they deem inappropriate, threatening, offensive,
44
+ or harmful.
45
+
46
+ Community leaders have the right and responsibility to remove, edit, or reject
47
+ comments, commits, code, wiki edits, issues, and other contributions that are
48
+ not aligned to this Code of Conduct, and will communicate reasons for moderation
49
+ decisions when appropriate.
50
+
51
+ ## Scope
52
+
53
+ This Code of Conduct applies within all community spaces, and also applies when
54
+ an individual is officially representing the community in public spaces.
55
+ Examples of representing our community include using an official email address,
56
+ posting via an official social media account, or acting as an appointed
57
+ representative at an online or offline event.
58
+
59
+ ## Enforcement
60
+
61
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
62
+ reported to the community leaders responsible for enforcement at
63
+ [INSERT CONTACT METHOD].
64
+ All complaints will be reviewed and investigated promptly and fairly.
65
+
66
+ All community leaders are obligated to respect the privacy and security of the
67
+ reporter of any incident.
68
+
69
+ ## Enforcement Guidelines
70
+
71
+ Community leaders will follow these Community Impact Guidelines in determining
72
+ the consequences for any action they deem in violation of this Code of Conduct:
73
+
74
+ ### 1. Correction
75
+
76
+ **Community Impact**: Use of inappropriate language or other behavior deemed
77
+ unprofessional or unwelcome in the community.
78
+
79
+ **Consequence**: A private, written warning from community leaders, providing
80
+ clarity around the nature of the violation and an explanation of why the
81
+ behavior was inappropriate. A public apology may be requested.
82
+
83
+ ### 2. Warning
84
+
85
+ **Community Impact**: A violation through a single incident or series of
86
+ actions.
87
+
88
+ **Consequence**: A warning with consequences for continued behavior. No
89
+ interaction with the people involved, including unsolicited interaction with
90
+ those enforcing the Code of Conduct, for a specified period of time. This
91
+ includes avoiding interactions in community spaces as well as external channels
92
+ like social media. Violating these terms may lead to a temporary or permanent
93
+ ban.
94
+
95
+ ### 3. Temporary Ban
96
+
97
+ **Community Impact**: A serious violation of community standards, including
98
+ sustained inappropriate behavior.
99
+
100
+ **Consequence**: A temporary ban from any sort of interaction or public
101
+ communication with the community for a specified period of time. No public or
102
+ private interaction with the people involved, including unsolicited interaction
103
+ with those enforcing the Code of Conduct, is allowed during this period.
104
+ Violating these terms may lead to a permanent ban.
105
+
106
+ ### 4. Permanent Ban
107
+
108
+ **Community Impact**: Demonstrating a pattern of violation of community
109
+ standards, including sustained inappropriate behavior, harassment of an
110
+ individual, or aggression toward or disparagement of classes of individuals.
111
+
112
+ **Consequence**: A permanent ban from any sort of public interaction within the
113
+ community.
114
+
115
+ ## Attribution
116
+
117
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage],
118
+ version 2.1, available at
119
+ [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
120
+
121
+ Community Impact Guidelines were inspired by
122
+ [Mozilla's code of conduct enforcement ladder][Mozilla CoC].
123
+
124
+ For answers to common questions about this code of conduct, see the FAQ at
125
+ [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
126
+ [https://www.contributor-covenant.org/translations][translations].
127
+
128
+ [homepage]: https://www.contributor-covenant.org
129
+ [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
130
+ [Mozilla CoC]: https://github.com/mozilla/diversity
131
+ [FAQ]: https://www.contributor-covenant.org/faq
132
+ [translations]: https://www.contributor-covenant.org/translations
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2025 airbearr
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,295 @@
1
+ # OxmlMaker
2
+
3
+ A Ruby gem for generating Microsoft Word DOCX files using OpenXML. Create professional documents with tables, paragraphs, and custom formatting programmatically.
4
+
5
+ ## Features
6
+
7
+ - ✅ **Generate Valid DOCX Files**: Creates Microsoft Word-compatible documents
8
+ - ✅ **Tables with Dynamic Data**: Populate tables from Ruby objects
9
+ - ✅ **Paragraphs and Text**: Simple text content with proper XML structure
10
+ - ✅ **Page Configuration**: Control page size, margins, headers/footers
11
+ - ✅ **Rails Integration**: Automatically detects Rails environment for file placement
12
+ - ✅ **ZIP-based Structure**: Properly formatted DOCX files using rubyzip
13
+ - ✅ **XML Safety**: Handles special characters and escaping
14
+ - ✅ **Public Directory Management**: Auto-creates output directories
15
+
16
+ ## Installation
17
+
18
+ Add this line to your application's Gemfile:
19
+
20
+ ```ruby
21
+ gem 'oxml_maker'
22
+ ```
23
+
24
+ And then execute:
25
+
26
+ ```bash
27
+ bundle install
28
+ ```
29
+
30
+ Or install it yourself as:
31
+
32
+ ```bash
33
+ gem install oxml_maker
34
+ ```
35
+
36
+ ## Quick Start
37
+
38
+ ```ruby
39
+ require 'oxml_maker'
40
+
41
+ # Define document parameters
42
+ params = {
43
+ sections: [
44
+ { paragraph: { text: "Welcome to OxmlMaker" } },
45
+ {
46
+ table: {
47
+ columns: [
48
+ { name: "Product", width: 3000 },
49
+ { name: "Price", width: 2000 }
50
+ ],
51
+ rows: [
52
+ {
53
+ cells: [
54
+ { value: :name, width: 3000 },
55
+ { value: :price, width: 2000 }
56
+ ]
57
+ }
58
+ ],
59
+ data: {
60
+ 0 => [
61
+ OpenStruct.new(name: "Widget", price: "$10.99"),
62
+ OpenStruct.new(name: "Gadget", price: "$25.50")
63
+ ]
64
+ },
65
+ font_size: 24
66
+ }
67
+ },
68
+ { paragraph: { text: "End of document" } }
69
+ ],
70
+ page_size: { width: 12240, height: 15840 },
71
+ page_margin: {
72
+ top: 1440, right: 1440, bottom: 1440, left: 1440,
73
+ header: 720, footer: 720, gutter: 0
74
+ }
75
+ }
76
+
77
+ # Create and generate the document
78
+ doc = OxmlMaker::Document.new(filename: "example.docx", params: params)
79
+ doc.create
80
+
81
+ # The file will be created in:
82
+ # - Rails apps: Rails.root/public/example.docx
83
+ # - Non-Rails: ./public/example.docx (auto-created)
84
+ ```
85
+
86
+ ## Usage Examples
87
+
88
+ ### Creating Tables
89
+
90
+ Tables can be populated with dynamic data from Ruby objects:
91
+
92
+ ```ruby
93
+ # Define table structure
94
+ table_config = {
95
+ columns: [
96
+ { name: "Name", width: 2000 },
97
+ { name: "Age", width: 1500 },
98
+ { name: "Email", width: 3000 }
99
+ ],
100
+ rows: [
101
+ {
102
+ cells: [
103
+ { value: :name, width: 2000 },
104
+ { value: :age, width: 1500 },
105
+ { value: :email, width: 3000 }
106
+ ]
107
+ }
108
+ ],
109
+ data: {
110
+ 0 => [
111
+ OpenStruct.new(name: "John Doe", age: 30, email: "john@example.com"),
112
+ OpenStruct.new(name: "Jane Smith", age: 25, email: "jane@example.com")
113
+ ]
114
+ },
115
+ font_size: 12
116
+ }
117
+
118
+ params = {
119
+ sections: [
120
+ { table: table_config }
121
+ ],
122
+ page_size: { width: 12240, height: 15840 },
123
+ page_margin: { top: 1440, right: 1440, bottom: 1440, left: 1440, header: 720, footer: 720, gutter: 0 }
124
+ }
125
+ ```
126
+
127
+ ### Adding Paragraphs
128
+
129
+ Simple text content with proper XML formatting:
130
+
131
+ ```ruby
132
+ params = {
133
+ sections: [
134
+ { paragraph: { text: "Document Title" } },
135
+ { paragraph: { text: "This is the first paragraph." } },
136
+ { paragraph: { text: "This is the second paragraph with more content." } }
137
+ ],
138
+ page_size: { width: 12240, height: 15840 },
139
+ page_margin: { top: 1440, right: 1440, bottom: 1440, left: 1440, header: 720, footer: 720, gutter: 0 }
140
+ }
141
+ ```
142
+
143
+ ### Output Location
144
+
145
+ The gem intelligently handles output location:
146
+
147
+ - **In Rails apps**: Files are saved to `Rails.root/public/`
148
+ - **Outside Rails**: Files are saved to `./public/` (created automatically)
149
+ - **Custom location**: Pass a custom directory to `copy_to_public(custom_dir)`
150
+
151
+ ## Development
152
+
153
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
154
+
155
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
156
+
157
+ ## Testing
158
+
159
+ ### Test Framework
160
+
161
+ The gem uses **Minitest** as its testing framework, which is included in Ruby's standard library. The test structure follows Ruby conventions:
162
+
163
+ - `test/test_helper.rb` - Common setup and helper methods
164
+ - `test/test_*.rb` - Individual test files for each class
165
+ - Tests run with `bundle exec rake test`
166
+
167
+ ### Current Test Coverage
168
+
169
+ - **63 tests, 274 assertions, 0 failures, 0 errors**
170
+ - Unit tests for all classes (Document, Paragraph, Table)
171
+ - Integration tests for complete workflows
172
+ - ZIP functionality tests with rubyzip
173
+ - Rails environment detection tests
174
+ - Error handling and edge case tests
175
+
176
+ ### Test Files
177
+
178
+ 1. **test_oxml_maker.rb** - Tests for the main module
179
+ 2. **test_paragraph.rb** - Tests for the Paragraph class
180
+ 3. **test_table.rb** - Tests for the Table class
181
+ 4. **test_document.rb** - Tests for the Document class
182
+ 5. **test_integration.rb** - Integration tests combining multiple classes
183
+ 6. **test_zip_functionality.rb** - ZIP creation and DOCX structure tests
184
+ 7. **test_full_workflow_integration.rb** - Complete end-to-end workflow tests
185
+
186
+ ### Running Tests
187
+
188
+ ```bash
189
+ # Run all tests
190
+ bundle exec rake test
191
+
192
+ # Run a specific test file
193
+ bundle exec ruby -Itest test/test_paragraph.rb
194
+
195
+ # Run a specific test method
196
+ bundle exec ruby -Itest test/test_paragraph.rb -n test_initialize_with_valid_hash
197
+ ```
198
+
199
+ ### Types of Tests
200
+
201
+ #### 1. Unit Tests
202
+ Test individual methods and classes in isolation:
203
+
204
+ ```ruby
205
+ def test_initialize_with_valid_hash
206
+ data = { text: "Hello, World!" }
207
+ paragraph = OxmlMaker::Paragraph.new(data)
208
+
209
+ assert_equal data, paragraph.data
210
+ end
211
+ ```
212
+
213
+ #### 2. Template/Output Tests
214
+ Verify that XML output contains expected elements:
215
+
216
+ ```ruby
217
+ def test_template_includes_xml_declaration
218
+ doc = OxmlMaker::Document.new(params: @sample_params)
219
+ template = doc.template
220
+
221
+ assert_includes template, '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
222
+ end
223
+ ```
224
+
225
+ #### 3. Integration Tests
226
+ Test multiple classes working together:
227
+
228
+ ```ruby
229
+ def test_document_with_mixed_content
230
+ params = {
231
+ sections: [
232
+ { paragraph: { text: "Document Title" } },
233
+ { table: table_data }
234
+ ],
235
+ page_size: { width: 12240, height: 15840 }
236
+ }
237
+
238
+ document = OxmlMaker::Document.new(params: params)
239
+ xml = document.template
240
+
241
+ assert_includes xml, "<w:t>Document Title</w:t>"
242
+ end
243
+ ```
244
+
245
+ #### 4. ZIP Functionality Tests
246
+ Verify DOCX file creation and structure:
247
+
248
+ ```ruby
249
+ def test_created_zip_is_valid_docx
250
+ doc = OxmlMaker::Document.new(filename: "test.docx", params: @params)
251
+ doc.create
252
+
253
+ # Verify ZIP structure matches DOCX requirements
254
+ Zip::File.open(@docx_path) do |zip|
255
+ assert zip.find_entry("[Content_Types].xml"), "Should contain Content Types"
256
+ assert zip.find_entry("_rels/.rels"), "Should contain relationships"
257
+ assert zip.find_entry("word/document.xml"), "Should contain main document"
258
+ end
259
+ end
260
+ ```
261
+
262
+ ### Testing Best Practices
263
+
264
+ 1. **Use Setup and Teardown** for consistent test environments
265
+ 2. **Test Edge Cases** including empty inputs, nil values, and special characters
266
+ 3. **Use Descriptive Test Names** that explain what is being tested
267
+ 4. **Test Both Success and Failure Paths** to ensure robust error handling
268
+ 5. **Mock External Dependencies** when needed (Rails environment, file systems)
269
+
270
+ ### Common Assertions
271
+
272
+ - `assert_equal expected, actual` - Test equality
273
+ - `assert_includes collection, item` - Test inclusion
274
+ - `assert_raises(ExceptionClass) { code }` - Test exceptions
275
+ - `assert condition` - Test truthiness
276
+ - `refute condition` - Test falsiness
277
+ - `assert_kind_of Class, object` - Test object type
278
+
279
+ ## Dependencies
280
+
281
+ - **rubyzip (~> 3.2)** - For ZIP file creation and DOCX generation
282
+ - **Standard Ruby libraries** (FileUtils, etc.)
283
+ - **Optional: Rails** - For automatic public directory detection
284
+
285
+ ## Contributing
286
+
287
+ Bug reports and pull requests are welcome on GitHub at https://github.com/mode-x/oxml_maker. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/mode-x/oxml_maker/blob/master/CODE_OF_CONDUCT.md).
288
+
289
+ ## License
290
+
291
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
292
+
293
+ ## Code of Conduct
294
+
295
+ Everyone interacting in the OxmlMaker project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/mode-x/oxml_maker/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "minitest/test_task"
5
+
6
+ Minitest::TestTask.create
7
+
8
+ require "rubocop/rake_task"
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: %i[test rubocop]
@@ -0,0 +1,109 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "zip"
4
+ require "fileutils"
5
+
6
+ # OxmlMaker module
7
+ module OxmlMaker
8
+ class Document
9
+ attr_accessor :params
10
+ attr_reader :filename
11
+
12
+ def initialize(filename: nil, params: {}, &block)
13
+ @filename = filename
14
+ @params = params
15
+ yield(self) if block_given?
16
+ end
17
+
18
+ def template
19
+ <<~XML
20
+ <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
21
+ <w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
22
+ <w:body>
23
+ #{generate_sections}
24
+ <w:sectPr>
25
+ <w:pgSz w:w='#{params[:page_size][:width]}' w:h='#{params[:page_size][:height]}'/>
26
+ <w:pgMar w:top='#{params[:page_margin][:top]}' w:right='#{params[:page_margin][:right]}' w:bottom='#{params[:page_margin][:bottom]}' w:left='#{params[:page_margin][:left]}' w:header='#{params[:page_margin][:header]}' w:footer='#{params[:page_margin][:footer]}' w:gutter='#{params[:page_margin][:gutter]}'/>
27
+ </w:sectPr>
28
+ </w:body>
29
+ </w:document>
30
+ XML
31
+ end
32
+
33
+ def create
34
+ prepare_paths
35
+ cleanup_temp_files
36
+ ensure_directories
37
+ write_document_xml
38
+ zip_docx_folder
39
+ convert_zip_to_docx
40
+ copy_to_public
41
+ cleanup_temp_files
42
+ end
43
+
44
+ private
45
+
46
+ def generate_sections
47
+ params[:sections].map do |section|
48
+ if section[:paragraph]
49
+ OxmlMaker::Paragraph.new(section[:paragraph]).template
50
+ elsif section[:table]
51
+ OxmlMaker::Table.new(section[:table]).template
52
+ end
53
+ end.join("\n")
54
+ end
55
+
56
+ def prepare_paths
57
+ @docx_root = File.join(__dir__, "docx")
58
+ @docx_word_path = File.join(@docx_root, "word")
59
+ @zip_path = File.join(__dir__, "document.zip")
60
+ @docx_path = File.join(__dir__, "document.docx")
61
+ end
62
+
63
+ def cleanup_temp_files
64
+ FileUtils.rm_f(@zip_path)
65
+ FileUtils.rm_f(@docx_path)
66
+ end
67
+
68
+ def ensure_directories
69
+ FileUtils.mkdir_p(@docx_word_path)
70
+ end
71
+
72
+ def write_document_xml
73
+ File.write(File.join(@docx_word_path, "document.xml"), template)
74
+ end
75
+
76
+ def zip_docx_folder
77
+ entries = Dir.glob(File.join(@docx_root, "**", "*"), File::FNM_DOTMATCH).select { |f| File.file?(f) }
78
+ Zip::File.open(@zip_path, create: true) do |zipfile|
79
+ entries.each do |file|
80
+ rel_path = file.sub("#{@docx_root}/", "")
81
+ zipfile.add(rel_path, file)
82
+ end
83
+ end
84
+ end
85
+
86
+ def convert_zip_to_docx
87
+ FileUtils.cp(@zip_path, @docx_path)
88
+ end
89
+
90
+ def copy_to_public(destination_dir = nil)
91
+ destination_dir ||= detect_public_dir
92
+ ensure_public_directory(destination_dir)
93
+ FileUtils.cp(@docx_path, File.join(destination_dir, filename))
94
+ end
95
+
96
+ def detect_public_dir
97
+ if defined?(Rails) && Rails.respond_to?(:root) && Rails.root
98
+ File.join(Rails.root, "public")
99
+ else
100
+ # For non-Rails environments (like testing), use local public directory
101
+ "public"
102
+ end
103
+ end
104
+
105
+ def ensure_public_directory(dir)
106
+ FileUtils.mkdir_p(dir)
107
+ end
108
+ end
109
+ end
@@ -0,0 +1,6 @@
1
+ <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2
+ <Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">
3
+ <Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>
4
+ <Default Extension="xml" ContentType="application/xml"/>
5
+ <Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/>
6
+ </Types>
@@ -0,0 +1,4 @@
1
+ <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2
+ <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
3
+ <Relationship Target="word/document.xml" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Id="rId1"/>
4
+ </Relationships>
@@ -0,0 +1,88 @@
1
+ <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2
+ <w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
3
+ <w:body>
4
+ <w:p>
5
+ <w:r>
6
+ <w:t>Test with special chars: & < > " '</w:t>
7
+ </w:r>
8
+ </w:p>
9
+
10
+ <w:tbl>
11
+ <w:tblPr>
12
+ <w:tblStyle w:val="DefaultTable"/>
13
+ <w:tblW w:w="10468" w:type="dxa"/>
14
+ <w:tblInd w:w="0" w:type="dxa"/>
15
+ <w:tblBorders>
16
+ <w:top w:color="666666" w:val="single" w:sz="4" w:space="0"/>
17
+ <w:left w:color="666666" w:val="single" w:sz="4" w:space="0"/>
18
+ <w:bottom w:color="666666" w:val="single" w:sz="4" w:space="0"/>
19
+ <w:right w:color="666666" w:val="single" w:sz="4" w:space="0"/>
20
+ <w:insideH w:color="666666" w:val="single" w:sz="4" w:space="0"/>
21
+ <w:insideV w:color="666666" w:val="single" w:sz="4" w:space="0"/>
22
+ </w:tblBorders>
23
+ <w:tblLayout w:type="fixed"/>
24
+ <w:tblLook w:val="0600"/>
25
+ </w:tblPr>
26
+ <w:tblGrid>
27
+ <w:gridCol w:w="3000"/>
28
+ </w:tblGrid>
29
+ <w:tr>
30
+ <w:tblPrEx>
31
+ <w:tblCellMar>
32
+ <w:top w:w="0" w:type="dxa"/>
33
+ <w:bottom w:w="0" w:type="dxa"/>
34
+ </w:tblCellMar>
35
+ </w:tblPrEx>
36
+ <w:trPr>
37
+ <w:tblAlign w:val="center"/>
38
+ </w:trPr>
39
+ <w:tc>
40
+ <w:tcPr>
41
+ <w:tcW w:w="3000"/>
42
+ </w:tcPr>
43
+ <w:p>
44
+ <w:pPr>
45
+ <w:jc w:val="center"/>
46
+ <w:rPr>
47
+ <w:b/>
48
+ </w:rPr>
49
+ </w:pPr>
50
+ <w:r>
51
+ <w:rPr>
52
+ <w:b/>
53
+ <w:sz w:val="22"/>
54
+ </w:rPr>
55
+ <w:t>Data & Info</w:t>
56
+ </w:r>
57
+ </w:p>
58
+ </w:tc>
59
+
60
+ </w:tr>
61
+ <w:tr>
62
+ <w:tc>
63
+ <w:tcPr>
64
+ <w:tcW w:w='3000' w:type='dxa'/>
65
+
66
+ <w:vAlign w:val="center"/>
67
+ </w:tcPr>
68
+ <w:p>
69
+ <w:pPr>
70
+ <w:jc w:val='center'/>
71
+ </w:pPr>
72
+ <w:r>
73
+ <w:rPr><w:sz w:val='22'/></w:rPr>
74
+ <w:t>Content with &lt;tags&gt; &amp; symbols</w:t>
75
+ </w:r>
76
+ </w:p>
77
+ </w:tc>
78
+
79
+ </w:tr>
80
+
81
+ </w:tbl>
82
+
83
+ <w:sectPr>
84
+ <w:pgSz w:w='12240' w:h='15840'/>
85
+ <w:pgMar w:top='1440' w:right='1440' w:bottom='1440' w:left='1440' w:header='720' w:footer='720' w:gutter='0'/>
86
+ </w:sectPr>
87
+ </w:body>
88
+ </w:document>
@@ -0,0 +1,32 @@
1
+ # frozen_string_literal: true
2
+
3
+ # OxmlMaker module
4
+ module OxmlMaker
5
+ # Represents a paragraph in an OXML document.
6
+ # It can be used to create structured text content within a Word document.
7
+ # The class is initialized with data that will be used to populate the paragraph.
8
+ # @param data [Hash] The data to be used in the paragraph.
9
+ # @example
10
+ # paragraph = Oxml::Paragraph.new(data: {text: "Hello, World!"})
11
+ # puts paragraph.template
12
+ # # Output: <w:p><w:r><w:t>Hello, World!</w:t></w:r></w:p>
13
+ class Paragraph
14
+ attr_reader :data
15
+
16
+ def initialize(data = {})
17
+ raise ArgumentError, "Data must be a Hash" unless data.is_a?(Hash)
18
+
19
+ @data = data
20
+ end
21
+
22
+ def template
23
+ <<~XML
24
+ <w:p>
25
+ <w:r>
26
+ <w:t>#{data[:text]}</w:t>
27
+ </w:r>
28
+ </w:p>
29
+ XML
30
+ end
31
+ end
32
+ end
@@ -0,0 +1,180 @@
1
+ # frozen_string_literal: true
2
+
3
+ # OxmlMaker module
4
+ module OxmlMaker
5
+ # Table class represents a table in an OXML document.
6
+ # Initialized with a hash containing :columns, :rows, :data, and :font_size.
7
+ class Table
8
+ attr_reader :table
9
+
10
+ def initialize(table)
11
+ @table = table
12
+ end
13
+
14
+ def template
15
+ <<~XML
16
+ <w:tbl>
17
+ <w:tblPr>
18
+ <w:tblStyle w:val="DefaultTable"/>
19
+ <w:tblW w:w="10468" w:type="dxa"/>
20
+ <w:tblInd w:w="0" w:type="dxa"/>
21
+ <w:tblBorders>
22
+ <w:top w:color="666666" w:val="single" w:sz="4" w:space="0"/>
23
+ <w:left w:color="666666" w:val="single" w:sz="4" w:space="0"/>
24
+ <w:bottom w:color="666666" w:val="single" w:sz="4" w:space="0"/>
25
+ <w:right w:color="666666" w:val="single" w:sz="4" w:space="0"/>
26
+ <w:insideH w:color="666666" w:val="single" w:sz="4" w:space="0"/>
27
+ <w:insideV w:color="666666" w:val="single" w:sz="4" w:space="0"/>
28
+ </w:tblBorders>
29
+ <w:tblLayout w:type="fixed"/>
30
+ <w:tblLook w:val="0600"/>
31
+ </w:tblPr>
32
+ <w:tblGrid>
33
+ #{table[:columns].map { |col| grid_col(col) }.join("\n")}
34
+ </w:tblGrid>
35
+ <w:tr>
36
+ <w:tblPrEx>
37
+ <w:tblCellMar>
38
+ <w:top w:w="0" w:type="dxa"/>
39
+ <w:bottom w:w="0" w:type="dxa"/>
40
+ </w:tblCellMar>
41
+ </w:tblPrEx>
42
+ <w:trPr>
43
+ <w:tblAlign w:val="center"/>
44
+ </w:trPr>
45
+ #{table[:columns].map { |column| header_row(column) }.join("\n")}
46
+ </w:tr>
47
+ #{table[:data].map { |_k, data| body_row(data) }.flatten.join("\n")}
48
+ </w:tbl>
49
+ XML
50
+ end
51
+
52
+ private
53
+
54
+ def grid_col(column)
55
+ width = column[:width] || 2000
56
+ "<w:gridCol w:w=\"#{width}\"/>"
57
+ end
58
+
59
+ def header_row(column)
60
+ <<~XML
61
+ <w:tc>
62
+ <w:tcPr>
63
+ <w:tcW w:w="#{column[:width] || 2000}"/>
64
+ </w:tcPr>
65
+ <w:p>
66
+ <w:pPr>
67
+ <w:jc w:val="center"/>
68
+ <w:rPr>
69
+ <w:b/>
70
+ </w:rPr>
71
+ </w:pPr>
72
+ <w:r>
73
+ <w:rPr>
74
+ <w:b/>
75
+ <w:sz w:val="#{table[:font_size] || 22}"/>
76
+ </w:rPr>
77
+ <w:t>#{column[:name]}</w:t>
78
+ </w:r>
79
+ </w:p>
80
+ </w:tc>
81
+ XML
82
+ end
83
+
84
+ def body_row(data)
85
+ data.map.with_index do |item, index|
86
+ <<~XML
87
+ <w:tr>
88
+ #{table[:rows][0][:cells].map { |cell| cell_xml(cell, item, index) }.join("\n")}
89
+ </w:tr>
90
+ XML
91
+ end.join("\n")
92
+ end
93
+
94
+ def cell_xml(cell, item, index)
95
+ width = cell[:width] || 2000
96
+ value = begin
97
+ item.send(cell[:value])
98
+ rescue StandardError
99
+ ""
100
+ end
101
+ if cell[:new_line]
102
+ <<~XML
103
+ <w:tc>
104
+ <w:tcPr>
105
+ <w:tcW w:w='#{width}' w:type='dxa'/>
106
+ <w:vAlign w:val="center"/>
107
+ </w:tcPr>
108
+ #{multi_line_cell_content(value)}
109
+ </w:tc>
110
+ XML
111
+ else
112
+ <<~XML
113
+ <w:tc>
114
+ <w:tcPr>
115
+ <w:tcW w:w='#{width}' w:type='dxa'/>
116
+ #{v_merge_tag(cell, index)}
117
+ <w:vAlign w:val="center"/>
118
+ </w:tcPr>
119
+ <w:p>
120
+ <w:pPr>
121
+ <w:jc w:val='center'/>
122
+ </w:pPr>
123
+ <w:r>
124
+ <w:rPr><w:sz w:val='#{table[:font_size] || 22}'/></w:rPr>
125
+ <w:t>#{cell_value(value)}</w:t>
126
+ </w:r>
127
+ </w:p>
128
+ </w:tc>
129
+ XML
130
+ end
131
+ end
132
+
133
+ def multi_line_cell_content(value)
134
+ if value.nil? || value.to_s.strip.empty?
135
+ <<~XML
136
+ <w:p>
137
+ <w:pPr>
138
+ <w:spacing w:after='0'/>
139
+ <w:jc w:val='center'/>
140
+ </w:pPr>
141
+ <w:r>
142
+ <w:rPr><w:sz w:val='22'/></w:rPr>
143
+ <w:t></w:t>
144
+ </w:r>
145
+ </w:p>
146
+ XML
147
+ else
148
+ value.split(", ").map do |line|
149
+ <<~XML
150
+ <w:p>
151
+ <w:pPr>
152
+ <w:spacing w:after='0'/>
153
+ <w:jc w:val='center'/>
154
+ </w:pPr>
155
+ <w:r>
156
+ <w:rPr><w:sz w:val='22'/></w:rPr>
157
+ <w:t>#{cell_value(line)}</w:t>
158
+ </w:r>
159
+ </w:p>
160
+ XML
161
+ end.join("\n")
162
+ end
163
+ end
164
+
165
+ def v_merge_tag(cell, index)
166
+ return "" unless cell[:v_merge]
167
+
168
+ index.zero? ? '<w:vMerge w:val="restart"/>' : '<w:vMerge w:val="continue"/>'
169
+ end
170
+
171
+ def cell_value(value)
172
+ value.to_s
173
+ .gsub("&", "&amp;")
174
+ .gsub("<", "&lt;")
175
+ .gsub(">", "&gt;")
176
+ .gsub('"', "&quot;")
177
+ .gsub("'", "&apos;")
178
+ end
179
+ end
180
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module OxmlMaker
4
+ VERSION = "0.1.1"
5
+ end
data/lib/oxml_maker.rb ADDED
@@ -0,0 +1,11 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "oxml_maker/version"
4
+ require_relative "oxml_maker/document"
5
+ require_relative "oxml_maker/paragraph"
6
+ require_relative "oxml_maker/table"
7
+
8
+ module OxmlMaker
9
+ class Error < StandardError; end
10
+ # Your code goes here...
11
+ end
@@ -0,0 +1,4 @@
1
+ module OxmlMaker
2
+ VERSION: String
3
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
4
+ end
metadata ADDED
@@ -0,0 +1,76 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: oxml_maker
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.1
5
+ platform: ruby
6
+ authors:
7
+ - airbearr
8
+ bindir: exe
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: rubyzip
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - "~>"
17
+ - !ruby/object:Gem::Version
18
+ version: '3.2'
19
+ type: :runtime
20
+ prerelease: false
21
+ version_requirements: !ruby/object:Gem::Requirement
22
+ requirements:
23
+ - - "~>"
24
+ - !ruby/object:Gem::Version
25
+ version: '3.2'
26
+ description: A Ruby gem for creating Microsoft Word DOCX files programmatically. Features
27
+ include tables with dynamic data, paragraphs, custom page settings, Rails integration,
28
+ and ZIP-based DOCX structure using rubyzip.
29
+ email:
30
+ - emmanuel.abia@corsearch.com
31
+ executables: []
32
+ extensions: []
33
+ extra_rdoc_files: []
34
+ files:
35
+ - ".rubocop.yml"
36
+ - CHANGELOG.md
37
+ - CODE_OF_CONDUCT.md
38
+ - LICENSE.txt
39
+ - README.md
40
+ - Rakefile
41
+ - lib/oxml_maker.rb
42
+ - lib/oxml_maker/document.rb
43
+ - lib/oxml_maker/docx/[Content_Types].xml
44
+ - lib/oxml_maker/docx/_rels/.rels
45
+ - lib/oxml_maker/docx/word/document.xml
46
+ - lib/oxml_maker/paragraph.rb
47
+ - lib/oxml_maker/table.rb
48
+ - lib/oxml_maker/version.rb
49
+ - sig/oxml_maker.rbs
50
+ homepage: https://github.com/mode-x/oxml_maker
51
+ licenses:
52
+ - MIT
53
+ metadata:
54
+ allowed_push_host: https://rubygems.org
55
+ homepage_uri: https://github.com/mode-x/oxml_maker
56
+ source_code_uri: https://github.com/mode-x/oxml_maker
57
+ changelog_uri: https://github.com/mode-x/oxml_maker/blob/main/CHANGELOG.md
58
+ rubygems_mfa_required: 'true'
59
+ rdoc_options: []
60
+ require_paths:
61
+ - lib
62
+ required_ruby_version: !ruby/object:Gem::Requirement
63
+ requirements:
64
+ - - ">="
65
+ - !ruby/object:Gem::Version
66
+ version: 3.1.0
67
+ required_rubygems_version: !ruby/object:Gem::Requirement
68
+ requirements:
69
+ - - ">="
70
+ - !ruby/object:Gem::Version
71
+ version: '0'
72
+ requirements: []
73
+ rubygems_version: 3.7.2
74
+ specification_version: 4
75
+ summary: Generate Microsoft Word DOCX files using OpenXML in Ruby
76
+ test_files: []