adamalbrecht/docx_replace — pull request #3 by beechnut (2014-05-06 15:10:44+00:00)
Title: Add 'matches' function

Takes in a regex and returns a string list of matches. This can be iterated on with a pattern if there are multiple similar matches in the document. Add MIT license attribute to Gemspec. Ignore .DS_Store (Mac file).

My implementation:

I have a .docx document template with many fields in the general form of `{@profile.some_attribute}`. I want anything that looks like that to be replaced with the actual value.

In my `app/controllers/municipalities_controller`:

```ruby
def export
# I have a Facade class in app/facades called Profile. This is modeled
# after Thoughtbot and Sandi Metz's developer rules:
# http://robots.thoughtbot.com/sandi-metz-rules-for-developers.
# You could just instantiate a regular model object here.
@profile = Profile.new( Municipality.find params[:id].titleize) )

# Initialize DocxReplace with my template, which is stored in lib/assets
doc = DocxReplace::Doc.new("#{Rails.root}/lib/assets/template.docx",
"#{Rails.root}/tmp")

# Get matches
matches = doc.uniq_matches(/\{(\@[\w\.]*)\}/)

# Replace all matches, one at a time, specifying :multiple_occurrences as true.
# I have to include the curly braces in the first argument to #replace because they
# are in the template.
matches.each {|match| doc.replace("{#{match}}", "#{eval match}", true)}

# Write the document back to a temporary file
tmp_file = Tempfile.new('word_template', "#{Rails.root}/tmp")
doc.commit(tmp_file)

send_file tmp_file.path, filename: "#{@profile.muni} Housing Needs Assessment.docx",
disposition: 'attachment'
end
```

In `app/views/municipalities/profile.html.haml`:

```haml
%a.btn.btn-lg.btn-primary{href: export_municipality_path(@profile.muni)}
Export to Word (.docx)
```

In `config/routes.rb`:

```ruby
...
resources :municipalities, except: [:index], path: '' do
...
get 'profile', on: :member
get 'export', on: :member
...
end
```