jr-paperclip 7.3.0

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.
Files changed (200) hide show
  1. checksums.yaml +7 -0
  2. data/.github/FUNDING.yml +3 -0
  3. data/.github/ISSUE_TEMPLATE/bug_report.md +38 -0
  4. data/.github/ISSUE_TEMPLATE/custom.md +10 -0
  5. data/.github/ISSUE_TEMPLATE/feature_request.md +20 -0
  6. data/.github/workflows/reviewdog.yml +23 -0
  7. data/.github/workflows/test.yml +46 -0
  8. data/.gitignore +19 -0
  9. data/.qlty/.gitignore +7 -0
  10. data/.qlty/qlty.toml +89 -0
  11. data/.rubocop.yml +1060 -0
  12. data/Appraisals +29 -0
  13. data/CONTRIBUTING.md +85 -0
  14. data/Gemfile +17 -0
  15. data/LICENSE +25 -0
  16. data/NEWS +567 -0
  17. data/README.md +1083 -0
  18. data/RELEASING.md +17 -0
  19. data/Rakefile +52 -0
  20. data/bin/console +11 -0
  21. data/features/basic_integration.feature +85 -0
  22. data/features/migration.feature +29 -0
  23. data/features/rake_tasks.feature +62 -0
  24. data/features/step_definitions/attachment_steps.rb +121 -0
  25. data/features/step_definitions/html_steps.rb +15 -0
  26. data/features/step_definitions/rails_steps.rb +271 -0
  27. data/features/step_definitions/s3_steps.rb +16 -0
  28. data/features/step_definitions/web_steps.rb +106 -0
  29. data/features/support/env.rb +12 -0
  30. data/features/support/file_helpers.rb +34 -0
  31. data/features/support/fixtures/boot_config.txt +15 -0
  32. data/features/support/fixtures/gemfile.txt +5 -0
  33. data/features/support/fixtures/preinitializer.txt +20 -0
  34. data/features/support/paths.rb +28 -0
  35. data/features/support/rails.rb +39 -0
  36. data/features/support/selectors.rb +19 -0
  37. data/features/support/webmock_setup.rb +8 -0
  38. data/gemfiles/7.0.gemfile +20 -0
  39. data/gemfiles/7.1.gemfile +20 -0
  40. data/gemfiles/7.2.gemfile +20 -0
  41. data/gemfiles/8.0.gemfile +20 -0
  42. data/gemfiles/8.1.gemfile +20 -0
  43. data/lib/generators/paperclip/USAGE +8 -0
  44. data/lib/generators/paperclip/paperclip_generator.rb +36 -0
  45. data/lib/generators/paperclip/templates/paperclip_migration.rb.erb +15 -0
  46. data/lib/jr-paperclip.rb +1 -0
  47. data/lib/paperclip/attachment.rb +634 -0
  48. data/lib/paperclip/attachment_registry.rb +60 -0
  49. data/lib/paperclip/callbacks.rb +42 -0
  50. data/lib/paperclip/content_type_detector.rb +85 -0
  51. data/lib/paperclip/errors.rb +34 -0
  52. data/lib/paperclip/file_command_content_type_detector.rb +28 -0
  53. data/lib/paperclip/filename_cleaner.rb +15 -0
  54. data/lib/paperclip/geometry.rb +157 -0
  55. data/lib/paperclip/geometry_detector_factory.rb +45 -0
  56. data/lib/paperclip/geometry_parser_factory.rb +31 -0
  57. data/lib/paperclip/glue.rb +18 -0
  58. data/lib/paperclip/has_attached_file.rb +116 -0
  59. data/lib/paperclip/helpers.rb +60 -0
  60. data/lib/paperclip/interpolations/plural_cache.rb +18 -0
  61. data/lib/paperclip/interpolations.rb +205 -0
  62. data/lib/paperclip/io_adapters/abstract_adapter.rb +75 -0
  63. data/lib/paperclip/io_adapters/attachment_adapter.rb +56 -0
  64. data/lib/paperclip/io_adapters/data_uri_adapter.rb +22 -0
  65. data/lib/paperclip/io_adapters/empty_string_adapter.rb +19 -0
  66. data/lib/paperclip/io_adapters/file_adapter.rb +26 -0
  67. data/lib/paperclip/io_adapters/http_url_proxy_adapter.rb +16 -0
  68. data/lib/paperclip/io_adapters/identity_adapter.rb +17 -0
  69. data/lib/paperclip/io_adapters/nil_adapter.rb +37 -0
  70. data/lib/paperclip/io_adapters/registry.rb +36 -0
  71. data/lib/paperclip/io_adapters/stringio_adapter.rb +36 -0
  72. data/lib/paperclip/io_adapters/uploaded_file_adapter.rb +44 -0
  73. data/lib/paperclip/io_adapters/uri_adapter.rb +78 -0
  74. data/lib/paperclip/locales/en.yml +18 -0
  75. data/lib/paperclip/locales/fr.yml +18 -0
  76. data/lib/paperclip/locales/gd.yml +20 -0
  77. data/lib/paperclip/logger.rb +21 -0
  78. data/lib/paperclip/matchers/have_attached_file_matcher.rb +54 -0
  79. data/lib/paperclip/matchers/validate_attachment_content_type_matcher.rb +101 -0
  80. data/lib/paperclip/matchers/validate_attachment_presence_matcher.rb +59 -0
  81. data/lib/paperclip/matchers/validate_attachment_size_matcher.rb +97 -0
  82. data/lib/paperclip/matchers.rb +64 -0
  83. data/lib/paperclip/media_type_spoof_detector.rb +93 -0
  84. data/lib/paperclip/missing_attachment_styles.rb +84 -0
  85. data/lib/paperclip/processor.rb +56 -0
  86. data/lib/paperclip/processor_helpers.rb +52 -0
  87. data/lib/paperclip/rails_environment.rb +21 -0
  88. data/lib/paperclip/railtie.rb +31 -0
  89. data/lib/paperclip/schema.rb +104 -0
  90. data/lib/paperclip/storage/filesystem.rb +99 -0
  91. data/lib/paperclip/storage/fog.rb +262 -0
  92. data/lib/paperclip/storage/s3.rb +497 -0
  93. data/lib/paperclip/storage.rb +3 -0
  94. data/lib/paperclip/style.rb +106 -0
  95. data/lib/paperclip/tempfile.rb +42 -0
  96. data/lib/paperclip/tempfile_factory.rb +22 -0
  97. data/lib/paperclip/thumbnail.rb +131 -0
  98. data/lib/paperclip/url_generator.rb +83 -0
  99. data/lib/paperclip/validators/attachment_content_type_validator.rb +95 -0
  100. data/lib/paperclip/validators/attachment_file_name_validator.rb +82 -0
  101. data/lib/paperclip/validators/attachment_file_type_ignorance_validator.rb +28 -0
  102. data/lib/paperclip/validators/attachment_presence_validator.rb +28 -0
  103. data/lib/paperclip/validators/attachment_size_validator.rb +126 -0
  104. data/lib/paperclip/validators/media_type_spoof_detection_validator.rb +29 -0
  105. data/lib/paperclip/validators.rb +73 -0
  106. data/lib/paperclip/version.rb +3 -0
  107. data/lib/paperclip.rb +215 -0
  108. data/lib/tasks/paperclip.rake +140 -0
  109. data/paperclip.gemspec +51 -0
  110. data/shoulda_macros/paperclip.rb +134 -0
  111. data/spec/database.yml +4 -0
  112. data/spec/paperclip/attachment_definitions_spec.rb +13 -0
  113. data/spec/paperclip/attachment_processing_spec.rb +79 -0
  114. data/spec/paperclip/attachment_registry_spec.rb +158 -0
  115. data/spec/paperclip/attachment_spec.rb +1617 -0
  116. data/spec/paperclip/content_type_detector_spec.rb +58 -0
  117. data/spec/paperclip/file_command_content_type_detector_spec.rb +40 -0
  118. data/spec/paperclip/filename_cleaner_spec.rb +13 -0
  119. data/spec/paperclip/geometry_detector_spec.rb +47 -0
  120. data/spec/paperclip/geometry_parser_spec.rb +73 -0
  121. data/spec/paperclip/geometry_spec.rb +267 -0
  122. data/spec/paperclip/glue_spec.rb +63 -0
  123. data/spec/paperclip/has_attached_file_spec.rb +78 -0
  124. data/spec/paperclip/integration_spec.rb +702 -0
  125. data/spec/paperclip/interpolations_spec.rb +270 -0
  126. data/spec/paperclip/io_adapters/abstract_adapter_spec.rb +160 -0
  127. data/spec/paperclip/io_adapters/attachment_adapter_spec.rb +167 -0
  128. data/spec/paperclip/io_adapters/data_uri_adapter_spec.rb +88 -0
  129. data/spec/paperclip/io_adapters/empty_string_adapter_spec.rb +17 -0
  130. data/spec/paperclip/io_adapters/file_adapter_spec.rb +134 -0
  131. data/spec/paperclip/io_adapters/http_url_proxy_adapter_spec.rb +142 -0
  132. data/spec/paperclip/io_adapters/identity_adapter_spec.rb +8 -0
  133. data/spec/paperclip/io_adapters/nil_adapter_spec.rb +25 -0
  134. data/spec/paperclip/io_adapters/registry_spec.rb +35 -0
  135. data/spec/paperclip/io_adapters/stringio_adapter_spec.rb +64 -0
  136. data/spec/paperclip/io_adapters/uploaded_file_adapter_spec.rb +146 -0
  137. data/spec/paperclip/io_adapters/uri_adapter_spec.rb +231 -0
  138. data/spec/paperclip/matchers/have_attached_file_matcher_spec.rb +19 -0
  139. data/spec/paperclip/matchers/validate_attachment_content_type_matcher_spec.rb +108 -0
  140. data/spec/paperclip/matchers/validate_attachment_presence_matcher_spec.rb +69 -0
  141. data/spec/paperclip/matchers/validate_attachment_size_matcher_spec.rb +88 -0
  142. data/spec/paperclip/media_type_spoof_detector_spec.rb +126 -0
  143. data/spec/paperclip/meta_class_spec.rb +30 -0
  144. data/spec/paperclip/paperclip_missing_attachment_styles_spec.rb +88 -0
  145. data/spec/paperclip/paperclip_spec.rb +196 -0
  146. data/spec/paperclip/plural_cache_spec.rb +37 -0
  147. data/spec/paperclip/processor_helpers_spec.rb +57 -0
  148. data/spec/paperclip/processor_spec.rb +26 -0
  149. data/spec/paperclip/rails_environment_spec.rb +30 -0
  150. data/spec/paperclip/rake_spec.rb +103 -0
  151. data/spec/paperclip/schema_spec.rb +298 -0
  152. data/spec/paperclip/storage/filesystem_spec.rb +102 -0
  153. data/spec/paperclip/storage/fog_spec.rb +606 -0
  154. data/spec/paperclip/storage/s3_live_spec.rb +188 -0
  155. data/spec/paperclip/storage/s3_spec.rb +1974 -0
  156. data/spec/paperclip/style_spec.rb +251 -0
  157. data/spec/paperclip/tempfile_factory_spec.rb +33 -0
  158. data/spec/paperclip/tempfile_spec.rb +35 -0
  159. data/spec/paperclip/thumbnail_spec.rb +504 -0
  160. data/spec/paperclip/url_generator_spec.rb +231 -0
  161. data/spec/paperclip/validators/attachment_content_type_validator_spec.rb +410 -0
  162. data/spec/paperclip/validators/attachment_file_name_validator_spec.rb +249 -0
  163. data/spec/paperclip/validators/attachment_presence_validator_spec.rb +85 -0
  164. data/spec/paperclip/validators/attachment_size_validator_spec.rb +325 -0
  165. data/spec/paperclip/validators/media_type_spoof_detection_validator_spec.rb +48 -0
  166. data/spec/paperclip/validators_spec.rb +179 -0
  167. data/spec/spec_helper.rb +52 -0
  168. data/spec/support/assertions.rb +84 -0
  169. data/spec/support/fake_model.rb +24 -0
  170. data/spec/support/fake_rails.rb +12 -0
  171. data/spec/support/fixtures/12k.png +0 -0
  172. data/spec/support/fixtures/50x50.png +0 -0
  173. data/spec/support/fixtures/5k.png +0 -0
  174. data/spec/support/fixtures/animated +0 -0
  175. data/spec/support/fixtures/animated.gif +0 -0
  176. data/spec/support/fixtures/animated.unknown +0 -0
  177. data/spec/support/fixtures/aws_s3.yml +13 -0
  178. data/spec/support/fixtures/bad.png +1 -0
  179. data/spec/support/fixtures/empty.html +1 -0
  180. data/spec/support/fixtures/empty.xlsx +0 -0
  181. data/spec/support/fixtures/fog.yml +8 -0
  182. data/spec/support/fixtures/rotated.jpg +0 -0
  183. data/spec/support/fixtures/s3.yml +8 -0
  184. data/spec/support/fixtures/sample.xlsm +0 -0
  185. data/spec/support/fixtures/spaced file.jpg +0 -0
  186. data/spec/support/fixtures/spaced file.png +0 -0
  187. data/spec/support/fixtures/text.txt +1 -0
  188. data/spec/support/fixtures/twopage.pdf +0 -0
  189. data/spec/support/fixtures/uppercase.PNG +0 -0
  190. data/spec/support/matchers/accept.rb +5 -0
  191. data/spec/support/matchers/exist.rb +5 -0
  192. data/spec/support/matchers/have_column.rb +23 -0
  193. data/spec/support/mock_attachment.rb +24 -0
  194. data/spec/support/mock_interpolator.rb +24 -0
  195. data/spec/support/mock_url_generator_builder.rb +26 -0
  196. data/spec/support/model_reconstruction.rb +72 -0
  197. data/spec/support/reporting.rb +11 -0
  198. data/spec/support/test_data.rb +13 -0
  199. data/spec/support/version_helper.rb +9 -0
  200. metadata +702 -0
data/README.md ADDED
@@ -0,0 +1,1083 @@
1
+ Paperclip
2
+ =========
3
+
4
+ [![Maintainability](https://qlty.sh/gh/jukra/projects/jr-paperclip/maintainability.svg)](https://qlty.sh/gh/jukra/projects/jr-paperclip)
5
+ ![Tests](https://github.com/jukra/jr-paperclip/actions/workflows/test.yml/badge.svg)
6
+ ![Reviewdog](https://github.com/jukra/jr-paperclip/actions/workflows/reviewdog.yml/badge.svg)
7
+
8
+ **Revived fork with active maintenance and support for Rails 7.0, 7.1, 8.0, and 8.1 on Ruby 3.2 and newer.**
9
+
10
+ If you are looking for older versions, please check the [original fork](https://github.com/kreeti/kt-paperclip).
11
+
12
+ Legacy versions were dropped to reduce maintenance overhead and keep up with updates in the project’s dependencies.
13
+
14
+ Additional maintainers are very welcome.
15
+
16
+ ---
17
+
18
+ We plan to support and maintain paperclip, as well as clean it up.
19
+
20
+ Please feel free to contribute Issues and pull requests.
21
+
22
+ ---
23
+
24
+ # Existing documentation
25
+
26
+ ## Documentation valid for `master` branch
27
+
28
+ ---
29
+
30
+ <!-- START doctoc generated TOC please keep comment here to allow auto update -->
31
+ <!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
32
+
33
+ - [Requirements](#requirements)
34
+ - [Ruby and Rails](#ruby-and-rails)
35
+ - [Image Processor](#image-processor)
36
+ - [`file`](#file)
37
+ - [Installation](#installation)
38
+ - [Quick Start](#quick-start)
39
+ - [Models](#models)
40
+ - [Migrations](#migrations)
41
+ - [Edit and New Views](#edit-and-new-views)
42
+ - [Edit and New Views with Simple Form](#edit-and-new-views-with-simple-form)
43
+ - [Controller](#controller)
44
+ - [View Helpers](#view-helpers)
45
+ - [Checking a File Exists](#checking-a-file-exists)
46
+ - [Deleting an Attachment](#deleting-an-attachment)
47
+ - [Usage](#usage)
48
+ - [Validations](#validations)
49
+ - [Internationalization (I18n)](#internationalization-i18n)
50
+ - [Security Validations](#security-validations)
51
+ - [Defaults](#defaults)
52
+ - [Migrations](#migrations-1)
53
+ - [Add Attachment Column To A Table](#add-attachment-column-to-a-table)
54
+ - [Schema Definition](#schema-definition)
55
+ - [Vintage Syntax](#vintage-syntax)
56
+ - [Storage](#storage)
57
+ - [Understanding Storage](#understanding-storage)
58
+ - [IO Adapters](#io-adapters)
59
+ - [Post Processing](#post-processing)
60
+ - [Custom Attachment Processors](#custom-attachment-processors)
61
+ - [Events](#events)
62
+ - [URI Obfuscation](#uri-obfuscation)
63
+ - [Checksum / Fingerprint](#checksum--fingerprint)
64
+ - [File Preservation for Soft-Delete](#file-preservation-for-soft-delete)
65
+ - [Dynamic Configuration](#dynamic-configuration)
66
+ - [Dynamic Styles:](#dynamic-styles)
67
+ - [Dynamic Processors:](#dynamic-processors)
68
+ - [Logging](#logging)
69
+ - [Deployment](#deployment)
70
+ - [Attachment Styles](#attachment-styles)
71
+ - [Testing](#testing)
72
+ - [Contributing](#contributing)
73
+ - [License](#license)
74
+
75
+ <!-- END doctoc generated TOC please keep comment here to allow auto update -->
76
+
77
+ Paperclip is intended as an easy file attachment library for ActiveRecord. The
78
+ intent behind it was to keep setup as easy as possible and to treat files as
79
+ much like other attributes as possible. This means they aren't saved to their
80
+ final locations on disk, nor are they deleted if set to nil, until
81
+ ActiveRecord::Base#save is called. It manages validations based on size and
82
+ presence, if required. It can transform its assigned image into thumbnails if
83
+ needed, and the prerequisites are as simple as installing ImageMagick (which,
84
+ for most modern Unix-based systems, is as easy as installing the right
85
+ packages). Attached files are saved to the filesystem and referenced in the
86
+ browser by an easily understandable specification, which has sensible and
87
+ useful defaults.
88
+
89
+ See the documentation for `has_attached_file` in [`Paperclip::ClassMethods`](http://www.rubydoc.info/gems/jr-paperclip/Paperclip/ClassMethods) for
90
+ more detailed options.
91
+
92
+ The complete [RDoc](http://www.rubydoc.info/gems/jr-paperclip) is online.
93
+
94
+ ---
95
+
96
+ Requirements
97
+ ------------
98
+
99
+ ### Ruby and Rails
100
+
101
+ Paperclip now requires Ruby version **>= 2.3** and Rails version **>= 4.2**
102
+ (only if you're going to use Paperclip with Ruby on Rails).
103
+
104
+ ### Image Processor
105
+
106
+ [ImageMagick](http://www.imagemagick.org) must be installed and Paperclip must have access to it. To ensure
107
+ that it does, on your command line, run `which convert` (one of the ImageMagick
108
+ utilities). This will give you the path where that utility is installed. For
109
+ example, it might return `/usr/local/bin/convert`.
110
+
111
+ Then, in your environment config file, let Paperclip know to look there by adding that
112
+ directory to its path.
113
+
114
+ In development mode, you might add this line to `config/environments/development.rb)`:
115
+
116
+ ```ruby
117
+ Paperclip.options[:command_path] = "/usr/local/bin/"
118
+ ```
119
+
120
+ If you're on Mac OS X, you'll want to run the following with [Homebrew](http://www.brew.sh):
121
+
122
+ brew install imagemagick
123
+
124
+ If you are dealing with pdf uploads or running the test suite, you'll also need
125
+ to install GhostScript. On Mac OS X, you can also install that using Homebrew:
126
+
127
+ brew install gs
128
+
129
+ If you are on Ubuntu (or any Debian base Linux distribution), you'll want to run
130
+ the following with apt-get:
131
+
132
+ sudo apt-get install imagemagick -y
133
+
134
+ ### `file`
135
+
136
+ The Unix [`file` command](https://en.wikipedia.org/wiki/File_(command)) is required for content-type checking.
137
+ This utility isn't available in Windows, but comes bundled with Ruby [Devkit](https://github.com/oneclick/rubyinstaller/wiki/Development-Kit),
138
+ so Windows users must make sure that the devkit is installed and added to the system `PATH`.
139
+
140
+ **Manual Installation**
141
+
142
+ If you're using Windows 7+ as a development environment, you may need to install the `file.exe` application manually. The `file spoofing` system in Paperclip 4+ relies on this; if you don't have it working, you'll receive `Validation failed: Upload file has an extension that does not match its contents.` errors.
143
+
144
+ To manually install, you should perform the following:
145
+
146
+ > **Download & install `file` from [this URL](http://gnuwin32.sourceforge.net/packages/file.htm)**
147
+
148
+ To test, you can use the image below:
149
+ ![untitled](https://cloud.githubusercontent.com/assets/1104431/4524452/a1f8cce4-4d44-11e4-872e-17adb96f79c9.png)
150
+
151
+ Next, you need to integrate with your environment - preferably through the `PATH` variable, or by changing your `config/environments/development.rb` file
152
+
153
+ **PATH**
154
+
155
+ 1. Click "Start"
156
+ 2. On "Computer", right-click and select "Properties"
157
+ 3. In Properties, select "Advanced System Settings"
158
+ 4. Click the "Environment Variables" button
159
+ 5. Locate the "PATH" var - at the end, add the path to your newly installed `file.exe` (typically `C:\Program Files (x86)\GnuWin32\bin`)
160
+ 6. Restart any CMD shells you have open & see if it works
161
+
162
+ OR
163
+
164
+ **Environment**
165
+
166
+ 1. Open `config/environments/development.rb`
167
+ 2. Add the following line: `Paperclip.options[:command_path] = 'C:\Program Files (x86)\GnuWin32\bin'`
168
+ 3. Restart your Rails server
169
+
170
+ Either of these methods will give your Rails setup access to the `file.exe` functionality, thus providing the ability to check the contents of a file (fixing the spoofing problem)
171
+
172
+ ---
173
+
174
+ Installation
175
+ ------------
176
+
177
+ Paperclip is distributed as a gem, which is how it should be used in your app.
178
+
179
+ Include the gem in your Gemfile:
180
+
181
+ ```ruby
182
+ gem "jr-paperclip", "~> 7.3"
183
+ ```
184
+
185
+ Or, if you want to get the latest, you can get master from the main paperclip repository:
186
+
187
+ ```ruby
188
+ gem "jr-paperclip", git: "git://github.com/jukra/jr-paperclip.git"
189
+ ```
190
+
191
+ If you're trying to use features that don't seem to be in the latest released gem, but are
192
+ mentioned in this README, then you probably need to specify the master branch if you want to
193
+ use them. This README is probably ahead of the latest released version if you're reading it
194
+ on GitHub.
195
+
196
+ For Non-Rails usage:
197
+
198
+ ```ruby
199
+ class ModuleName < ActiveRecord::Base
200
+ include Paperclip::Glue
201
+ ...
202
+ end
203
+ ```
204
+
205
+ ---
206
+
207
+ Quick Start
208
+ -----------
209
+
210
+ ### Models
211
+
212
+ ```ruby
213
+ class User < ActiveRecord::Base
214
+ has_attached_file :avatar, styles: { medium: "300x300>", thumb: "100x100>" }, default_url: "/images/:style/missing.png"
215
+ validates_attachment_content_type :avatar, content_type: /\Aimage\/.*\z/
216
+ end
217
+ ```
218
+
219
+ ### Migrations
220
+
221
+
222
+ Assuming you have a `users` table, add an `avatar` column to the `users` table:
223
+ ```ruby
224
+ class AddAvatarColumnsToUsers < ActiveRecord::Migration
225
+ def up
226
+ add_attachment :users, :avatar
227
+ end
228
+
229
+ def down
230
+ remove_attachment :users, :avatar
231
+ end
232
+ end
233
+ ```
234
+
235
+ (Or you can use the Rails migration generator: `rails generate paperclip user avatar`)
236
+
237
+ ### Edit and New Views
238
+ Make sure you have corresponding methods in your controller:
239
+ ```erb
240
+ <%= form_for @user, url: users_path, html: { multipart: true } do |form| %>
241
+ <%= form.file_field :avatar %>
242
+ <%= form.submit %>
243
+ <% end %>
244
+ ```
245
+
246
+ ### Edit and New Views with [Simple Form](https://github.com/plataformatec/simple_form)
247
+
248
+ ```erb
249
+ <%= simple_form_for @user, url: users_path do |form| %>
250
+ <%= form.input :avatar, as: :file %>
251
+ <%= form.submit %>
252
+ <% end %>
253
+ ```
254
+
255
+ ### Controller
256
+
257
+ ```ruby
258
+ def create
259
+ @user = User.create(user_params)
260
+ end
261
+
262
+ private
263
+
264
+ # Use strong_parameters for attribute whitelisting
265
+ # Be sure to update your create() and update() controller methods.
266
+
267
+ def user_params
268
+ params.require(:user).permit(:avatar)
269
+ end
270
+ ```
271
+
272
+ ### View Helpers
273
+ Add these to the view where you want your images displayed:
274
+ ```erb
275
+ <%= image_tag @user.avatar.url %>
276
+ <%= image_tag @user.avatar.url(:medium) %>
277
+ <%= image_tag @user.avatar.url(:thumb) %>
278
+ ```
279
+
280
+ ### Checking a File Exists
281
+
282
+ There are two methods for checking if a file exists:
283
+
284
+ - `file?` and `present?` checks if the `_file_name` field is populated
285
+ - `exists?` checks if the file exists (will perform a TCP connection if stored in the cloud)
286
+
287
+ Keep this in mind if you are checking if files are present in a loop. The first
288
+ version is significantly more performant, but has different semantics.
289
+
290
+ ### Deleting an Attachment
291
+
292
+ Set the attribute to `nil` and save.
293
+
294
+ ```ruby
295
+ @user.avatar = nil
296
+ @user.save
297
+ ```
298
+ ---
299
+
300
+ Usage
301
+ -----
302
+
303
+ The basics of Paperclip are quite simple: Declare that your model has an
304
+ attachment with the `has_attached_file` method, and give it a name.
305
+
306
+ Paperclip will wrap up to four attributes (all prefixed with that attachment's name,
307
+ so you can have multiple attachments per model if you wish) and give them a
308
+ friendly front end. These attributes are:
309
+
310
+ * `<attachment>_file_name`
311
+ * `<attachment>_file_size`
312
+ * `<attachment>_content_type`
313
+ * `<attachment>_updated_at`
314
+
315
+ By default, only `<attachment>_file_name` is required for Paperclip to operate.
316
+ You'll need to add `<attachment>_content_type` in case you want to use content type
317
+ validation.
318
+
319
+ More information about the options passed to `has_attached_file` is available in the
320
+ documentation of [`Paperclip::ClassMethods`](http://www.rubydoc.info/gems/jr-paperclip/Paperclip/ClassMethods).
321
+
322
+ Validations
323
+ -----------
324
+
325
+ For validations, Paperclip introduces several validators to validate your attachment:
326
+
327
+ * `AttachmentContentTypeValidator`
328
+ * `AttachmentPresenceValidator`
329
+ * `AttachmentSizeValidator`
330
+
331
+ Example Usage:
332
+
333
+ ```ruby
334
+ validates :avatar, attachment_presence: true
335
+ validates_with AttachmentPresenceValidator, attributes: :avatar
336
+ validates_with AttachmentSizeValidator, attributes: :avatar, less_than: 1.megabytes
337
+
338
+ ```
339
+
340
+ Validators can also be defined using the old helper style:
341
+
342
+ * `validates_attachment_presence`
343
+ * `validates_attachment_content_type`
344
+ * `validates_attachment_size`
345
+
346
+ Example Usage:
347
+
348
+ ```ruby
349
+ validates_attachment_presence :avatar
350
+ ```
351
+
352
+ You can also define multiple validations on a single attachment using `validates_attachment`:
353
+
354
+ ```ruby
355
+ validates_attachment :avatar, presence: true,
356
+ content_type: "image/jpeg",
357
+ size: { in: 0..10.kilobytes }
358
+ ```
359
+
360
+ _NOTE: Post-processing will not even **start** if the attachment is not valid
361
+ according to the validations. Your callbacks and processors will **only** be
362
+ called with valid attachments._
363
+
364
+ ```ruby
365
+ class Message < ActiveRecord::Base
366
+ has_attached_file :asset, styles: { thumb: "100x100#" }
367
+
368
+ before_post_process :skip_for_audio
369
+
370
+ def skip_for_audio
371
+ ! %w(audio/ogg application/ogg).include?(asset_content_type)
372
+ end
373
+ end
374
+ ```
375
+
376
+ If you have other validations that depend on assignment order, the recommended
377
+ course of action is to prevent the assignment of the attachment until
378
+ afterwards, then assign manually:
379
+
380
+ ```ruby
381
+ class Book < ActiveRecord::Base
382
+ has_attached_file :document, styles: { thumbnail: "60x60#" }
383
+ validates_attachment :document, content_type: "application/pdf"
384
+ validates_something_else # Other validations that conflict with Paperclip's
385
+ end
386
+
387
+ class BooksController < ApplicationController
388
+ def create
389
+ @book = Book.new(book_params)
390
+ @book.document = params[:book][:document]
391
+ @book.save
392
+ respond_with @book
393
+ end
394
+
395
+ private
396
+
397
+ def book_params
398
+ params.require(:book).permit(:title, :author)
399
+ end
400
+ end
401
+ ```
402
+
403
+ **A note on content_type validations and security**
404
+
405
+ You should ensure that you validate files to be only those MIME types you
406
+ explicitly want to support. If you don't, you could be open to
407
+ <a href="https://www.owasp.org/index.php/Testing_for_Stored_Cross_site_scripting_(OWASP-DV-002)">XSS attacks</a>
408
+ if a user uploads a file with a malicious HTML payload.
409
+
410
+ If you're only interested in images, restrict your allowed content_types to
411
+ image-y ones:
412
+
413
+ ```ruby
414
+ validates_attachment :avatar,
415
+ content_type: ["image/jpeg", "image/gif", "image/png"]
416
+ ```
417
+
418
+ `Paperclip::ContentTypeDetector` will attempt to match a file's extension to an
419
+ inferred content_type, regardless of the actual contents of the file.
420
+
421
+ ### Duplicate error messages
422
+
423
+ By default Paperclip will copy validation errors from the attribute to the base
424
+ of your model. Depending on how you display your validation errors, this can lead
425
+ to confusing duplicate errors (one on the attribute and another referring to the
426
+ base model).
427
+
428
+ You can override this behaviour with the `add_validation_errors_to` option. By
429
+ default this is set to `:both` but can be set to either `:attribute` or `:base`.
430
+
431
+ * `:both` creates errors on both the attribute and base model.
432
+ * `:attribute` only creates an error on the attribute of the model.
433
+ * `:base` only creates an error on the base model.
434
+
435
+ You can set this option globally:
436
+
437
+ `Paperclip.options[:add_validation_errors_to] = :attribute`
438
+
439
+ or pass it in to an individual validation declaration:
440
+
441
+ `validates_attachment :document, content_type: { content_type: "application/pdf" }, add_validation_errors_to: :attribute`
442
+
443
+ ---
444
+
445
+ Internationalization (I18n)
446
+ ---------------------------
447
+
448
+ For using or adding locale files in different languages, check the project
449
+ https://github.com/kreeti/paperclip-i18n.
450
+
451
+ Security Validations
452
+ ====================
453
+
454
+ Thanks to a report from [Egor Homakov](http://homakov.blogspot.com/) we have
455
+ taken steps to prevent people from spoofing Content-Types and getting data
456
+ you weren't expecting onto your server.
457
+
458
+ NOTE: Starting at version 4.0.0, all attachments are *required* to include a
459
+ content_type validation, a file_name validation, or to explicitly state that
460
+ they're not going to have either. *Paperclip will raise an error* if you do not
461
+ do this.
462
+
463
+ ```ruby
464
+ class ActiveRecord::Base
465
+ has_attached_file :avatar
466
+ # Validate content type
467
+ validates_attachment_content_type :avatar, content_type: /\Aimage/
468
+ # Validate filename
469
+ validates_attachment_file_name :avatar, matches: [/png\z/, /jpe?g\z/]
470
+ # Explicitly do not validate
471
+ do_not_validate_attachment_file_type :avatar
472
+ end
473
+ ```
474
+
475
+ This keeps Paperclip secure-by-default, and will prevent people trying to mess
476
+ with your filesystem.
477
+
478
+ NOTE: Also starting at version 4.0.0, Paperclip has another validation that
479
+ cannot be turned off. This validation will prevent content type spoofing. That
480
+ is, uploading a PHP document (for example) as part of the EXIF tags of a
481
+ well-formed JPEG. This check is limited to the media type (the first part of the
482
+ MIME type, so, 'text' in `text/plain`). This will prevent HTML documents from
483
+ being uploaded as JPEGs, but will not prevent GIFs from being uploaded with a
484
+ `.jpg` extension. This validation will only add validation errors to the form. It
485
+ will not cause errors to be raised.
486
+
487
+ This can sometimes cause false validation errors in applications that use custom
488
+ file extensions. In these cases you may wish to add your custom extension to the
489
+ list of content type mappings by creating `config/initializers/paperclip.rb`:
490
+
491
+ ```ruby
492
+ # Allow ".foo" as an extension for files with the MIME type "text/plain".
493
+ Paperclip.options[:content_type_mappings] = {
494
+ foo: %w(text/plain)
495
+ }
496
+ ```
497
+
498
+ ---
499
+
500
+ Defaults
501
+ --------
502
+ Global defaults for all your Paperclip attachments can be defined by changing the Paperclip::Attachment.default_options Hash. This can be useful for setting your default storage settings per example so you won't have to define them in every `has_attached_file` definition.
503
+
504
+ If you're using Rails, you can define a Hash with default options in `config/application.rb` or in any of the `config/environments/*.rb` files on config.paperclip_defaults. These will get merged into `Paperclip::Attachment.default_options` as your Rails app boots. An example:
505
+
506
+ ```ruby
507
+ module YourApp
508
+ class Application < Rails::Application
509
+ # Other code...
510
+
511
+ config.paperclip_defaults = { storage: :fog, fog_credentials: { provider: "Local", local_root: "#{Rails.root}/public"}, fog_directory: "", fog_host: "localhost"}
512
+ end
513
+ end
514
+ ```
515
+
516
+ Another option is to directly modify the `Paperclip::Attachment.default_options` Hash - this method works for non-Rails applications or is an option if you prefer to place the Paperclip default settings in an initializer.
517
+
518
+ An example Rails initializer would look something like this:
519
+
520
+ ```ruby
521
+ Paperclip::Attachment.default_options[:storage] = :fog
522
+ Paperclip::Attachment.default_options[:fog_credentials] = { provider: "Local", local_root: "#{Rails.root}/public"}
523
+ Paperclip::Attachment.default_options[:fog_directory] = ""
524
+ Paperclip::Attachment.default_options[:fog_host] = "http://localhost:3000"
525
+ ```
526
+ ---
527
+
528
+ Migrations
529
+ ----------
530
+
531
+ Paperclip defines several migration methods which can be used to create the necessary columns in your
532
+ model. There are two types of helper methods to aid in this, as follows:
533
+
534
+ ### Add Attachment Column To A Table
535
+
536
+ The `attachment` helper can be used when creating a table:
537
+
538
+ ```ruby
539
+ class CreateUsersWithAttachments < ActiveRecord::Migration
540
+ def up
541
+ create_table :users do |t|
542
+ t.attachment :avatar
543
+ end
544
+ end
545
+
546
+ # This is assuming you are only using the users table for Paperclip attachment. Drop with care!
547
+ def down
548
+ drop_table :users
549
+ end
550
+ end
551
+ ```
552
+
553
+ You can also use the `change` method, instead of the `up`/`down` combination above, as shown below:
554
+
555
+ ```ruby
556
+ class CreateUsersWithAttachments < ActiveRecord::Migration
557
+ def change
558
+ create_table :users do |t|
559
+ t.attachment :avatar
560
+ end
561
+ end
562
+ end
563
+ ```
564
+
565
+ ### Schema Definition
566
+
567
+ Alternatively, the `add_attachment` and `remove_attachment` methods can be used to add new Paperclip columns to an existing table:
568
+
569
+ ```ruby
570
+ class AddAttachmentColumnsToUsers < ActiveRecord::Migration
571
+ def up
572
+ add_attachment :users, :avatar
573
+ end
574
+
575
+ def down
576
+ remove_attachment :users, :avatar
577
+ end
578
+ end
579
+ ```
580
+
581
+ Or you can do this with the `change` method:
582
+
583
+ ```ruby
584
+ class AddAttachmentColumnsToUsers < ActiveRecord::Migration
585
+ def change
586
+ add_attachment :users, :avatar
587
+ end
588
+ end
589
+ ```
590
+
591
+ ### Vintage Syntax
592
+
593
+ Vintage syntax (such as `t.has_attached_file` and `drop_attached_file`) is still supported in
594
+ Paperclip 3.x, but you're advised to update those migration files to use this new syntax.
595
+
596
+ ---
597
+
598
+ Storage
599
+ -------
600
+
601
+ Paperclip ships with 3 storage adapters:
602
+
603
+ * File Storage (`storage: :filesystem`)
604
+ * S3 Storage (via `aws-sdk-s3`) (`storage: :s3`)
605
+ * Fog Storage (`storage: :fog`)
606
+
607
+ If you would like to use Paperclip with another storage, you can install these
608
+ gems along side with Paperclip:
609
+
610
+ * [paperclip-azure](https://github.com/supportify/paperclip-azure)
611
+ * [paperclip-azure-storage](https://github.com/gmontard/paperclip-azure-storage)
612
+ * [paperclip-dropbox](https://github.com/janko-m/paperclip-dropbox)
613
+
614
+ ### Understanding Storage
615
+
616
+ The files that are assigned as attachments are, by default, placed in the
617
+ directory specified by the `:path` option to `has_attached_file`. By default, this
618
+ location is `:rails_root/public/system/:class/:attachment/:id_partition/:style/:filename`.
619
+ This location was chosen because, on standard Capistrano deployments, the
620
+ `public/system` directory can be symlinked to the app's shared directory, meaning it
621
+ survives between deployments. For example, using that `:path`, you may have a
622
+ file at
623
+
624
+ /data/myapp/releases/20081229172410/public/system/users/avatar/000/000/013/small/my_pic.png
625
+
626
+ _**NOTE**: This is a change from previous versions of Paperclip, but is overall a
627
+ safer choice for the default file store._
628
+
629
+ You may also choose to store your files using Amazon's S3 service. To do so, include
630
+ the `aws-sdk-s3` gem in your Gemfile:
631
+
632
+ ```ruby
633
+ gem 'aws-sdk-s3'
634
+ ```
635
+
636
+ And then you can specify using S3 from `has_attached_file`.
637
+ You can find more information about configuring and using S3 storage in
638
+ [the `Paperclip::Storage::S3` documentation](http://www.rubydoc.info/gems/jr-paperclip/Paperclip/Storage/S3).
639
+
640
+ Files on the local filesystem (and in the Rails app's public directory) will be
641
+ available to the internet at large. If you require access control, it's
642
+ possible to place your files in a different location. You will need to change
643
+ both the `:path` and `:url` options in order to make sure the files are unavailable
644
+ to the public. Both `:path` and `:url` allow the same set of interpolated
645
+ variables.
646
+
647
+ ---
648
+
649
+ IO Adapters
650
+ -----------
651
+
652
+ When a file is uploaded or attached, it can be in one of a few different input
653
+ forms, from Rails' UploadedFile object to a StringIO to a Tempfile or even a
654
+ simple String that is a URL that points to an image.
655
+
656
+ Paperclip will accept, by default, many of these sources. It also is capable of
657
+ handling even more with a little configuration. The IO Adapters that handle
658
+ images from non-local sources are not enabled by default. They can be enabled by
659
+ adding a line similar to the following into `config/initializers/paperclip.rb`:
660
+
661
+ ```ruby
662
+ Paperclip::DataUriAdapter.register
663
+ ```
664
+
665
+ It's best to only enable a remote-loading adapter if you need it. Otherwise
666
+ there's a chance that someone can gain insight into your internal network
667
+ structure using it as a vector.
668
+
669
+ The following adapters are *not* loaded by default:
670
+
671
+ * `Paperclip::UriAdapter` - which accepts a `URI` instance.
672
+ * `Paperclip::HttpUrlProxyAdapter` - which accepts a `http` string.
673
+ * `Paperclip::DataUriAdapter` - which accepts a Base64-encoded `data:` string.
674
+
675
+ ---
676
+
677
+ Post Processing
678
+ ---------------
679
+
680
+ Paperclip supports an extensible selection of post-processors. When you define
681
+ a set of styles for an attachment, by default it is expected that those
682
+ "styles" are actually "thumbnails." These are processed by
683
+ `Paperclip::Thumbnail`. For backward compatibility reasons you can pass either
684
+ a single geometry string, or an array containing a geometry and a format that
685
+ the file will be converted to, like so:
686
+
687
+ ```ruby
688
+ has_attached_file :avatar, styles: { thumb: ["32x32#", :png] }
689
+ ```
690
+
691
+ This will convert the "thumb" style to a 32x32 square in PNG format, regardless
692
+ of what was uploaded. If the format is not specified, it is kept the same (e.g.
693
+ JPGs will remain JPGs). `Paperclip::Thumbnail` uses ImageMagick to process
694
+ images; [ImageMagick's geometry documentation](http://www.imagemagick.org/script/command-line-processing.php#geometry)
695
+ has more information on the accepted style formats.
696
+
697
+ For more fine-grained control of the conversion process, `source_file_options` and `convert_options` can be used to pass flags and settings directly to ImageMagick's powerful Convert tool, [documented here](https://www.imagemagick.org/script/convert.php). For example:
698
+
699
+ ```ruby
700
+ has_attached_file :image, styles: { regular: ['800x800>', :png]},
701
+ source_file_options: { regular: "-density 96 -depth 8 -quality 85" },
702
+ convert_options: { regular: "-posterize 3"}
703
+ ```
704
+
705
+ ImageMagick supports a number of environment variables for controlling its resource limits. For example, you can enforce memory or execution time limits by setting the following variables in your application's process environment:
706
+
707
+ * `MAGICK_MEMORY_LIMIT=128MiB`
708
+ * `MAGICK_MAP_LIMIT=64MiB`
709
+ * `MAGICK_TIME_LIMIT=30`
710
+
711
+ For a full list of variables and description, see [ImageMagick's resources documentation](http://www.imagemagick.org/script/resources.php).
712
+
713
+ ---
714
+
715
+ Custom Attachment Processors
716
+ -------
717
+
718
+ You can write your own custom attachment processors to carry out tasks like
719
+ adding watermarks, compressing images, or encrypting files. Custom processors
720
+ must be defined within the `Paperclip` module, inherit from
721
+ `Paperclip::Processor` (see [`lib/paperclip/processor.rb`](https://github.com/jukra/jr-paperclip/blob/master/lib/paperclip/processor.rb)),
722
+ and implement a `make` method that returns a `File`. All files in your Rails
723
+ app's `lib/paperclip` and `lib/paperclip_processors` directories will be
724
+ automatically loaded by Paperclip. Processors are specified using the
725
+ `:processors` option to `has_attached_file`:
726
+
727
+ ```ruby
728
+ has_attached_file :scan, styles: { text: { quality: :better } },
729
+ processors: [:ocr]
730
+ ```
731
+
732
+ This would load the hypothetical class `Paperclip::Ocr`, and pass it the
733
+ options hash `{ quality: :better }`, along with the uploaded file.
734
+
735
+ Multiple processors can be specified, and they will be invoked in the order
736
+ they are defined in the `:processors` array. Each successive processor is given
737
+ the result from the previous processor. All processors receive the same
738
+ parameters, which are defined in the `:styles` hash. For example, assuming we
739
+ had this definition:
740
+
741
+ ```ruby
742
+ has_attached_file :scan, styles: { text: { quality: :better } },
743
+ processors: [:rotator, :ocr]
744
+ ```
745
+
746
+ Both the `:rotator` processor and the `:ocr` processor would receive the
747
+ options `{ quality: :better }`. If a processor receives an option it doesn't
748
+ recognise, it's expected to ignore it.
749
+
750
+ _NOTE: Because processors operate by turning the original attachment into the
751
+ styles, no processors will be run if there are no styles defined._
752
+
753
+ If you're interested in caching your thumbnail's width, height, and size in the
754
+ database, take a look at the [paperclip-meta](https://github.com/teeparham/paperclip-meta)
755
+ gem.
756
+
757
+ Also, if you're interested in generating the thumbnail on-the-fly, you might want
758
+ to look into the [attachment_on_the_fly](https://github.com/drpentode/Attachment-on-the-Fly)
759
+ gem.
760
+
761
+ Paperclip's thumbnail generator (see [`lib/paperclip/thumbnail.rb`](lib/paperclip/thumbnail.rb))
762
+ is implemented as a processor, and may be a good reference for writing your own
763
+ processors.
764
+
765
+ ---
766
+
767
+ Events
768
+ ------
769
+
770
+ Before and after the Post Processing step, Paperclip calls back to the model
771
+ with a few callbacks, allowing the model to change or cancel the processing
772
+ step. The callbacks are `before_post_process` and `after_post_process` (which
773
+ are called before and after the processing of each attachment), and the
774
+ attachment-specific `before_<attachment>_post_process` and
775
+ `after_<attachment>_post_process`. The callbacks are intended to be as close to
776
+ normal ActiveRecord callbacks as possible, so if you return false (specifically
777
+ \- returning nil is not the same) in a `before_filter`, the post processing step
778
+ will halt. Returning false in an `after_filter` will not halt anything, but you
779
+ can access the model and the attachment if necessary.
780
+
781
+ _NOTE: Post processing will not even **start** if the attachment is not valid
782
+ according to the validations. Your callbacks and processors will **only** be
783
+ called with valid attachments._
784
+
785
+ ```ruby
786
+ class Message < ActiveRecord::Base
787
+ has_attached_file :asset, styles: { thumb: "100x100#" }
788
+
789
+ before_post_process :skip_for_audio
790
+
791
+ def skip_for_audio
792
+ ! %w(audio/ogg application/ogg).include?(asset_content_type)
793
+ end
794
+ end
795
+ ```
796
+
797
+ ---
798
+
799
+ URI Obfuscation
800
+ ---------------
801
+
802
+ Paperclip has an interpolation called `:hash` for obfuscating filenames of
803
+ publicly-available files.
804
+
805
+ Example Usage:
806
+
807
+ ```ruby
808
+ has_attached_file :avatar, {
809
+ url: "/system/:hash.:extension",
810
+ hash_secret: "longSecretString"
811
+ }
812
+ ```
813
+
814
+
815
+ The `:hash` interpolation will be replaced with a unique hash made up of whatever
816
+ is specified in `:hash_data`. The default value for `:hash_data` is `":class/:attachment/:id/:style/:updated_at"`.
817
+
818
+ `:hash_secret` is required - an exception will be raised if `:hash` is used without `:hash_secret` present.
819
+
820
+ For more on this feature, read [the author's own explanation](https://github.com/thoughtbot/paperclip/pull/416)
821
+
822
+ Checksum / Fingerprint
823
+ -------
824
+
825
+ A checksum of the original file assigned will be placed in the model if it
826
+ has an attribute named fingerprint. Following the user model migration example
827
+ above, the migration would look like the following:
828
+
829
+ ```ruby
830
+ class AddAvatarFingerprintColumnToUser < ActiveRecord::Migration
831
+ def up
832
+ add_column :users, :avatar_fingerprint, :string
833
+ end
834
+
835
+ def down
836
+ remove_column :users, :avatar_fingerprint
837
+ end
838
+ end
839
+ ```
840
+
841
+ The algorithm can be specified using a configuration option; it defaults to MD5
842
+ for backwards compatibility with Paperclip 5 and earlier.
843
+
844
+ ```ruby
845
+ has_attached_file :some_attachment, adapter_options: { hash_digest: Digest::SHA256 }
846
+ ```
847
+
848
+ Run `CLASS=User ATTACHMENT=avatar rake paperclip:refresh:fingerprints` after
849
+ changing the digest on existing attachments to update the fingerprints in the
850
+ database.
851
+
852
+ File Preservation for Soft-Delete
853
+ -------
854
+
855
+ An option is available to preserve attachments in order to play nicely with soft-deleted models. (acts_as_paranoid, paranoia, etc.)
856
+
857
+ ```ruby
858
+ has_attached_file :some_attachment, {
859
+ preserve_files: true,
860
+ }
861
+ ```
862
+
863
+ This will prevent ```some_attachment``` from being wiped out when the model gets destroyed, so it will still exist when the object is restored later.
864
+
865
+ ---
866
+
867
+ Dynamic Configuration
868
+ ---------------------
869
+
870
+ Callable objects (lambdas, Procs) can be used in a number of places for dynamic
871
+ configuration throughout Paperclip. This strategy exists in a number of
872
+ components of the library but is most significant in the possibilities for
873
+ allowing custom styles and processors to be applied for specific model
874
+ instances, rather than applying defined styles and processors across all
875
+ instances.
876
+
877
+ ### Dynamic Styles:
878
+
879
+ Imagine a user model that had different styles based on the role of the user.
880
+ Perhaps some users are bosses (e.g. a User model instance responds to `#boss?`)
881
+ and merit a bigger avatar thumbnail than regular users. The configuration to
882
+ determine what style parameters are to be used based on the user role might
883
+ look as follows where a boss will receive a `300x300` thumbnail otherwise a
884
+ `100x100` thumbnail will be created.
885
+
886
+ ```ruby
887
+ class User < ActiveRecord::Base
888
+ has_attached_file :avatar, styles: lambda { |attachment| { thumb: (attachment.instance.boss? ? "300x300>" : "100x100>") } }
889
+ end
890
+ ```
891
+
892
+ ### Dynamic Processors:
893
+
894
+ Another contrived example is a user model that is aware of which file processors
895
+ should be applied to it (beyond the implied `thumbnail` processor invoked when
896
+ `:styles` are defined). Perhaps we have a watermark processor available and it is
897
+ only used on the avatars of certain models. The configuration for this might be
898
+ where the instance is queried for which processors should be applied to it.
899
+ Presumably some users might return `[:thumbnail, :watermark]` for its
900
+ processors, where a defined `watermark` processor is invoked after the
901
+ `thumbnail` processor already defined by Paperclip.
902
+
903
+ ```ruby
904
+ class User < ActiveRecord::Base
905
+ has_attached_file :avatar, processors: lambda { |instance| instance.processors }
906
+ attr_accessor :processors
907
+ end
908
+ ```
909
+
910
+ ---
911
+
912
+ Logging
913
+ ----------
914
+
915
+ By default, Paperclip outputs logging according to your logger level. If you want to disable logging (e.g. during testing) add this into your environment's configuration:
916
+ ```ruby
917
+ Your::Application.configure do
918
+ ...
919
+ Paperclip.options[:log] = false
920
+ ...
921
+ end
922
+ ```
923
+
924
+ More information in the [rdocs](https://www.rubydoc.info/gems/jr-paperclip/Paperclip.options)
925
+
926
+ ---
927
+
928
+ Deployment
929
+ ----------
930
+
931
+ To make Capistrano symlink the `public/system` directory so that attachments
932
+ survive new deployments, set the `linked_dirs` option in your `config/deploy.rb`
933
+ file:
934
+
935
+ ```ruby
936
+ set :linked_dirs, fetch(:linked_dirs, []).push('public/system')
937
+ ```
938
+
939
+ ### Attachment Styles
940
+
941
+ Paperclip is aware of new attachment styles you have added in previous deploys. The only thing you should do after each deployment is to call
942
+ `rake paperclip:refresh:missing_styles`. It will store current attachment styles in `RAILS_ROOT/public/system/paperclip_attachments.yml`
943
+ by default. You can change it by:
944
+
945
+ ```ruby
946
+ Paperclip.registered_attachments_styles_path = '/tmp/config/paperclip_attachments.yml'
947
+ ```
948
+
949
+ Here is an example for Capistrano:
950
+
951
+ ```ruby
952
+ namespace :paperclip do
953
+ desc "build missing paperclip styles"
954
+ task :build_missing_styles do
955
+ on roles(:app) do
956
+ within release_path do
957
+ with rails_env: fetch(:rails_env) do
958
+ execute :rake, "paperclip:refresh:missing_styles"
959
+ end
960
+ end
961
+ end
962
+ end
963
+ end
964
+
965
+ after("deploy:compile_assets", "paperclip:build_missing_styles")
966
+ ```
967
+
968
+ Now you don't have to remember to refresh thumbnails in production every time you add a new style.
969
+ Unfortunately, it does not work with dynamic styles - it just ignores them.
970
+
971
+ If you already have a working app and don't want `rake paperclip:refresh:missing_styles` to refresh old pictures, you need to tell
972
+ Paperclip about existing styles. Simply create a `paperclip_attachments.yml` file by hand. For example:
973
+
974
+ ```ruby
975
+ class User < ActiveRecord::Base
976
+ has_attached_file :avatar, styles: { thumb: 'x100', croppable: '600x600>', big: '1000x1000>' }
977
+ end
978
+
979
+ class Book < ActiveRecord::Base
980
+ has_attached_file :cover, styles: { small: 'x100', large: '1000x1000>' }
981
+ has_attached_file :sample, styles: { thumb: 'x100' }
982
+ end
983
+ ```
984
+
985
+ Then in `RAILS_ROOT/public/system/paperclip_attachments.yml`:
986
+
987
+ ```yml
988
+ ---
989
+ :User:
990
+ :avatar:
991
+ - :thumb
992
+ - :croppable
993
+ - :big
994
+ :Book:
995
+ :cover:
996
+ - :small
997
+ - :large
998
+ :sample:
999
+ - :thumb
1000
+ ```
1001
+
1002
+ ---
1003
+
1004
+ Testing
1005
+ -------
1006
+
1007
+ Paperclip provides rspec-compatible matchers for testing attachments. See the
1008
+ documentation on [Paperclip::Shoulda::Matchers](http://www.rubydoc.info/gems/jr-paperclip/Paperclip/Shoulda/Matchers)
1009
+ for more information.
1010
+
1011
+ **Parallel Tests**
1012
+
1013
+ Because of the default `path` for Paperclip storage, if you try to run tests in
1014
+ parallel, you may find that files get overwritten because the same path is being
1015
+ calculated for them in each test process. While this fix works for
1016
+ parallel_tests, a similar concept should be used for any other mechanism for
1017
+ running tests concurrently.
1018
+
1019
+ ```ruby
1020
+ if ENV['PARALLEL_TEST_GROUPS']
1021
+ Paperclip::Attachment.default_options[:path] = ":rails_root/public/system/:rails_env/#{ENV['TEST_ENV_NUMBER'].to_i}/:class/:attachment/:id_partition/:filename"
1022
+ else
1023
+ Paperclip::Attachment.default_options[:path] = ":rails_root/public/system/:rails_env/:class/:attachment/:id_partition/:filename"
1024
+ end
1025
+ ```
1026
+
1027
+ The important part here being the inclusion of `ENV['TEST_ENV_NUMBER']`, or a
1028
+ similar mechanism for whichever parallel testing library you use.
1029
+
1030
+ **Integration Tests**
1031
+
1032
+ Using integration tests with FactoryBot may save multiple copies of
1033
+ your test files within the app. To avoid this, specify a custom path in
1034
+ the `config/environments/test.rb` like so:
1035
+
1036
+ ```ruby
1037
+ Paperclip::Attachment.default_options[:path] = "#{Rails.root}/spec/test_files/:class/:id_partition/:style.:extension"
1038
+ ```
1039
+
1040
+ Then, make sure to delete that directory after the test suite runs by adding
1041
+ this to `spec_helper.rb`.
1042
+
1043
+ ```ruby
1044
+ config.after(:suite) do
1045
+ FileUtils.rm_rf(Dir["#{Rails.root}/spec/test_files/"])
1046
+ end
1047
+ ```
1048
+
1049
+ **Example of test configuration with Factory Bot**
1050
+
1051
+
1052
+ ```ruby
1053
+ FactoryBot.define do
1054
+ factory :user do
1055
+ avatar { File.new("#{Rails.root}/spec/support/fixtures/image.jpg") }
1056
+ end
1057
+ end
1058
+ ```
1059
+ ---
1060
+
1061
+ Contributing
1062
+ ------------
1063
+
1064
+ If you'd like to contribute a feature or bugfix: Thanks! To make sure your
1065
+ fix/feature has a high chance of being included, please read the following
1066
+ guidelines:
1067
+
1068
+ 1. Post a [pull request](https://github.com/jukra/jr-paperclip/compare/).
1069
+ 2. Make sure there are tests! We will not accept any patch that is not tested.
1070
+ It's a rare time when explicit tests aren't needed. If you have questions
1071
+ about writing tests for paperclip, please open a
1072
+ [GitHub issue](https://github.com/jukra/jr-paperclip/issues/new).
1073
+
1074
+ Please see [`CONTRIBUTING.md`](./CONTRIBUTING.md) for more details on contributing and running test.
1075
+
1076
+ Thank you to all [the contributors](https://github.com/jukra/jr-paperclip/graphs/contributors)!
1077
+
1078
+ License
1079
+ -------
1080
+
1081
+ Copyright &copy; 2020-2021 Kreeti Technologies Pvt. Ltd.
1082
+ Copyright &copy; 2008-2017 thoughtbot, inc.
1083
+ It is free software, and may be redistributed under the terms specified in the MIT-LICENSE file.