decorator_dryer 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 57534e692dcdc6bfc6a30bf1ba81d3392acd5aa9970c61c4a301ac680f8cbb35
4
+ data.tar.gz: 26e905c85521618775dc1276e9e9435f7839d003cc99137719b40d4f673b7c2d
5
+ SHA512:
6
+ metadata.gz: 8e0f3540a44117a74423b51b30d871303d61bfc8f48bfd874c915fe8c2b40ecbaae19180adf5c824dd4013ec6c365487f1fefbcdcacd5fca7a3548e1ae408285
7
+ data.tar.gz: 445f24bce804cf151f0967f18bd6edeabb37769390dcf2720655d51f9eb10ee8c369781ad10d2a93b6363ba804ddf956dae66cf922b62f92e821057853d2446f
data/.gitignore ADDED
@@ -0,0 +1,11 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+
10
+ # rspec failure tracking
11
+ .rspec_status
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,40 @@
1
+ AllCops:
2
+ TargetRubyVersion: 2.6
3
+ SuggestExtensions: false
4
+
5
+ Layout/LineLength:
6
+ Max: 120
7
+
8
+ Metrics/AbcSize:
9
+ Max: 40
10
+ Exclude:
11
+ - spec/**/*
12
+
13
+ Metrics/BlockLength:
14
+ Exclude:
15
+ - spec/**/*
16
+
17
+ Style/ConditionalAssignment:
18
+ EnforcedStyle: assign_inside_condition
19
+
20
+ Metrics/CyclomaticComplexity:
21
+ Max: 10
22
+
23
+ Metrics/MethodLength:
24
+ Max: 30
25
+ Exclude:
26
+ - spec/**/*
27
+
28
+ Metrics/PerceivedComplexity:
29
+ Max: 10
30
+
31
+ Style/Documentation:
32
+ Enabled: false
33
+
34
+ Style/StringLiterals:
35
+ Enabled: true
36
+ EnforcedStyle: double_quotes
37
+
38
+ Style/StringLiteralsInInterpolation:
39
+ Enabled: true
40
+ EnforcedStyle: double_quotes
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2023-11-09
4
+
5
+ - Initial release
@@ -0,0 +1,84 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or
22
+ advances of any kind
23
+ * Trolling, insulting or derogatory comments, and personal or political attacks
24
+ * Public or private harassment
25
+ * Publishing others' private information, such as a physical or email
26
+ address, without their explicit permission
27
+ * Other conduct which could reasonably be considered inappropriate in a
28
+ professional setting
29
+
30
+ ## Enforcement Responsibilities
31
+
32
+ Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
33
+
34
+ Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
35
+
36
+ ## Scope
37
+
38
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
39
+
40
+ ## Enforcement
41
+
42
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at mark@tyne-solutions.com. All complaints will be reviewed and investigated promptly and fairly.
43
+
44
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
45
+
46
+ ## Enforcement Guidelines
47
+
48
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
49
+
50
+ ### 1. Correction
51
+
52
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
53
+
54
+ **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
55
+
56
+ ### 2. Warning
57
+
58
+ **Community Impact**: A violation through a single incident or series of actions.
59
+
60
+ **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
61
+
62
+ ### 3. Temporary Ban
63
+
64
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
65
+
66
+ **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
67
+
68
+ ### 4. Permanent Ban
69
+
70
+ **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
71
+
72
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
73
+
74
+ ## Attribution
75
+
76
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
77
+ available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
78
+
79
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
80
+
81
+ [homepage]: https://www.contributor-covenant.org
82
+
83
+ For answers to common questions about this code of conduct, see the FAQ at
84
+ https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
data/Gemfile ADDED
@@ -0,0 +1,6 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ # Specify your gem's dependencies in decorator_dryer.gemspec
6
+ gemspec
data/Gemfile.lock ADDED
@@ -0,0 +1,61 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ decorator_dryer (0.1.0)
5
+
6
+ GEM
7
+ remote: https://rubygems.org/
8
+ specs:
9
+ ast (2.4.2)
10
+ diff-lcs (1.5.0)
11
+ json (2.7.1)
12
+ language_server-protocol (3.17.0.3)
13
+ parallel (1.24.0)
14
+ parser (3.2.2.4)
15
+ ast (~> 2.4.1)
16
+ racc
17
+ racc (1.7.3)
18
+ rainbow (3.1.1)
19
+ rake (13.1.0)
20
+ regexp_parser (2.8.3)
21
+ rexml (3.2.6)
22
+ rspec (3.12.0)
23
+ rspec-core (~> 3.12.0)
24
+ rspec-expectations (~> 3.12.0)
25
+ rspec-mocks (~> 3.12.0)
26
+ rspec-core (3.12.2)
27
+ rspec-support (~> 3.12.0)
28
+ rspec-expectations (3.12.3)
29
+ diff-lcs (>= 1.2.0, < 2.0)
30
+ rspec-support (~> 3.12.0)
31
+ rspec-mocks (3.12.6)
32
+ diff-lcs (>= 1.2.0, < 2.0)
33
+ rspec-support (~> 3.12.0)
34
+ rspec-support (3.12.1)
35
+ rubocop (1.59.0)
36
+ json (~> 2.3)
37
+ language_server-protocol (>= 3.17.0)
38
+ parallel (~> 1.10)
39
+ parser (>= 3.2.2.4)
40
+ rainbow (>= 2.2.2, < 4.0)
41
+ regexp_parser (>= 1.8, < 3.0)
42
+ rexml (>= 3.2.5, < 4.0)
43
+ rubocop-ast (>= 1.30.0, < 2.0)
44
+ ruby-progressbar (~> 1.7)
45
+ unicode-display_width (>= 2.4.0, < 3.0)
46
+ rubocop-ast (1.30.0)
47
+ parser (>= 3.2.1.0)
48
+ ruby-progressbar (1.13.0)
49
+ unicode-display_width (2.5.0)
50
+
51
+ PLATFORMS
52
+ x86_64-darwin-20
53
+
54
+ DEPENDENCIES
55
+ decorator_dryer!
56
+ rake (~> 13.0)
57
+ rspec (~> 3.12)
58
+ rubocop (~> 1.7)
59
+
60
+ BUNDLED WITH
61
+ 2.4.21
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2023 Mark Harbison
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,248 @@
1
+ # Decorator Dryer
2
+
3
+ Welcome to Decorator Dryer! The aim of this gem is to help you write smaller, DRYer, easier to maintain, decorators.
4
+
5
+ Decorator Dryer contains a collection of formatters that cover some of the more common things that developers do in their decorators. On top of those formatters is a layer of shortcuts to help you reduce the amount of code in your decorator classes.
6
+
7
+ This is not a fully-formed decorator framework. Decorator Dryer is intended as a companion for Draper.
8
+
9
+ ## Installation
10
+
11
+ Add this line to your application's Gemfile:
12
+
13
+ ```ruby
14
+ gem 'draper'
15
+ gem 'decorator_dryer'
16
+ ```
17
+
18
+ And then execute:
19
+
20
+ $ bundle install
21
+
22
+ ## Configuration
23
+
24
+ ### Formatters
25
+
26
+ The formatters in Decorator Dryer use a set of default formats for things like dates and times.
27
+
28
+ If you are happy with the defaults, you can skip this section. However, if you would like to set your own defaults, you can do so with an initializer.
29
+
30
+ ```ruby
31
+ DecoratorDryer.configure do |config|
32
+ config.date_format = "%Y-%m-%d"
33
+ config.humanized_date_format = "%d/%m/%Y"
34
+ config.datetime_format = "%Y-%m-%d %H:%M"
35
+ config.humanized_datetime_format = "%H:%M %d/%m/%Y"
36
+ config.time_format = "%H:%M"
37
+ end
38
+ ```
39
+
40
+ ### Attachments
41
+
42
+ Decorator Dryer also provides shortcuts for attachments. There will be more detail on these shortcuts in later sections.
43
+
44
+ This can also be configured via an initializer.
45
+
46
+ ```ruby
47
+ DecoratorDryer.configure do |config|
48
+ config.attachment_shortcuts.mode = :none
49
+ config.attachment_shortcuts.default_preview_transform = :none
50
+ end
51
+ ```
52
+
53
+ Attachment shortcuts are disabled by default. To enable them, you can set `config.attachment_shortcuts.mode = :active_storage` Please note that this gem currently only provides shortcuts for Active Storage attachments.
54
+
55
+ You can also set a default transform for your attachment previews.
56
+
57
+ This could either be a variant, with something like:
58
+ `config.attachment_shortcuts.default_preview_transform = :thumb`
59
+ Or, a representation with something like:
60
+ `config.attachment_shortcuts.default_preview_transform = { resize: "400x" }`
61
+
62
+ ## Usage
63
+
64
+ Decorator Dryer is not a complete decorator library. It is intended for use alongside Draper. Why reinvent the wheel when there is already such a good option out there?
65
+
66
+ You can use Decorator Dryer by either adding the shortcuts to your decorator classes or by directly calling the formatters from within your decorator methods.
67
+
68
+ ### Shortcuts
69
+
70
+ ```ruby
71
+ class PersonDecorator < Draper::Decorator
72
+ include DecoratorDryer
73
+
74
+ to_date_format :date_of_birth
75
+ to_datetime_format :moment_of_birth
76
+ to_time_format :lunch_time
77
+ to_precision_number :salary, precision: 2
78
+ to_attachment :profile_picture
79
+ end
80
+ ```
81
+
82
+ #### to_date_format
83
+
84
+ This shortcut adds a method to your decorator that returns the formatted date. It can accept 1 or more attributes of type Date, DateTime, or Time.
85
+
86
+ ```ruby
87
+ class PersonDecorator < Draper::Decorator
88
+ include DecoratorDryer
89
+
90
+ to_date_format :date_of_birth, :date_of_graduation
91
+ end
92
+
93
+ date_of_birth = Date.new(2000, 1, 1)
94
+ date_of_graduation = Date.new(2018, 6, 6)
95
+ person = Person.create(date_of_birth: date_of_birth, date_of_graduation: date_of_graduation)
96
+ person.decorate.date_of_birth # ==> '2000-01-01'
97
+ person.decorate.date_of_graduation # ==> '2018-06-06'
98
+ ```
99
+
100
+ This shortcut uses the gem's default date format (%Y-%m-%d), or the format set in your initializer.
101
+
102
+ You could also provide a context when initializing your decorator, and tell it to return dates in a humanized format. The humanized format can also be set in your initializer.
103
+
104
+ ```ruby
105
+ date_of_birth = Date.new(2000, 1, 1)
106
+ person = Person.create(date_of_birth: date_of_birth)
107
+ person.decorate(context: { humanize: true }).date_of_birth # ==> '01/01/2000'
108
+ ```
109
+
110
+ #### to_datetime_format
111
+
112
+ This shortcut adds a method to your decorator that returns the formatted datetime. It can accept 1 or more attributes of type DateTime or Time.
113
+
114
+ ```ruby
115
+ class PersonDecorator < Draper::Decorator
116
+ include DecoratorDryer
117
+
118
+ to_datetime_format :moment_of_birth, :moment_of_graduation
119
+ end
120
+
121
+ moment_of_birth = DateTime.new(2000, 1, 1, 12, 30, 59)
122
+ moment_of_graduation = DateTime.new(2018, 6, 6, 17, 00, 03)
123
+ person = Person.create(moment_of_birth: moment_of_birth, moment_of_graduation: moment_of_graduation)
124
+ person.decorate.moment_of_birth # ==> '2000-01-01 12:30'
125
+ person.decorate.moment_of_graduation # ==> '2018-06-06 17:00'
126
+ ```
127
+
128
+ This shortcut uses the gem's default datetime format (%Y-%m-%d %H:%M), or the format set in your initializer.
129
+
130
+ You could also provide a context when initializing your decorator, and tell it to return datetimes in a humanized format. The humanized format can also be set in your initializer.
131
+
132
+ ```ruby
133
+ moment_of_birth = DateTime.new(2000, 1, 1, 12, 30, 59)
134
+ person = Person.create(moment_of_birth: moment_of_birth)
135
+ person.decorate(context: { humanize: true }).moment_of_birth # ==> '12:30 01/01/2000'
136
+ ```
137
+
138
+ #### to_time_format
139
+
140
+ This shortcut adds a method to your decorator that returns the formatted time. It can accept 1 or more attributes of type DateTime or Time.
141
+
142
+ ```ruby
143
+ class PersonDecorator < Draper::Decorator
144
+ include DecoratorDryer
145
+
146
+ to_time_format :moment_of_birth, :moment_of_graduation
147
+ end
148
+
149
+ moment_of_birth = Time.new(2000, 1, 1, 12, 30, 59)
150
+ moment_of_graduation = Time.new(2018, 6, 6, 17, 00, 03)
151
+ person = Person.create(moment_of_birth: moment_of_birth, moment_of_graduation: moment_of_graduation)
152
+ person.decorate.moment_of_birth # ==> '12:30'
153
+ person.decorate.moment_of_graduation # ==> '17:00'
154
+ ```
155
+
156
+ This shortcut uses the gem's default time format (%H:%M), or the format set in your initializer. This shortcut does not have an option for a humanized format.
157
+
158
+ #### to_precision_number
159
+
160
+ This shortcut adds a method to your decorator that returns the provided numbers as strings with a specific number of decimal places. It can accept 1 or more number attributes and a precision. If you would like to use different precisions for different attributes, you can use the shortcut multiple times.
161
+
162
+ ```ruby
163
+ class PersonDecorator < Draper::Decorator
164
+ include DecoratorDryer
165
+
166
+ to_precision_number :salary, :coffee_budget, precision: 2
167
+ to_precision_number :height_in_meters, precision: 3
168
+ end
169
+
170
+ person = Person.create(salary: 1000, coffee_budget: 20, height_in_meters: 1.8516)
171
+ person.decorate.salary # ==> '1000.00'
172
+ person.decorate.coffee_budget # ==> '20.00'
173
+ person.decorate.height_in_meters # ==> '1.852'
174
+ ```
175
+
176
+ #### to_attachment
177
+
178
+ To use this shortcut, you need to enable it in your initializer (see details above).
179
+
180
+ This shortcut adds 4 methods to your decorator for each of the specified attachments. Those methods return the attachment's URL, filename, signed-id, and preview-URL.
181
+
182
+ The preview is based on the gem's default preview-transform, or the transform set in your initializer. If you would like to override the transform in your decorator, you can provide a `preview_transform` option along with the attachment attributes. If you would like to use different transforms for different attributes, you can use the shortcut multiple times.
183
+
184
+ ```ruby
185
+ class PersonDecorator < Draper::Decorator
186
+ include DecoratorDryer
187
+
188
+ to_attachment :profile_picture, :resume
189
+ to_attachment :birth_certificate, preview_transform: :thumbnail
190
+ end
191
+
192
+ person = Person.create(profile_picture: ..., resume: ..., birth_certificate: ...)
193
+ person.decorate.profile_picture_url
194
+ person.decorate.profile_picture_name
195
+ person.decorate.profile_picture_preview
196
+ person.decorate.profile_picture_signed_id
197
+ ...
198
+ ```
199
+
200
+ ### Formatters
201
+
202
+ It is also possible to use the formatters directly, without the shortcuts. This gives you the flexibility to set different method names or use additional logic.
203
+
204
+ ```ruby
205
+ class PersonDecorator < Draper::Decorator
206
+ include DecoratorDryer
207
+
208
+ def first_birthday
209
+ format_date(object.date_of_birth)
210
+ end
211
+
212
+ def birth_datetime
213
+ format_datetime(moment_of_birth)
214
+ end
215
+
216
+ def when_is_lunch
217
+ format_time(lunch_time)
218
+ end
219
+
220
+ def income
221
+ format_precision_number(salary, precision: 2)
222
+ end
223
+ end
224
+ ```
225
+
226
+ ## To Do
227
+
228
+ * Enable formats to be overridden when calling shortcuts.
229
+ * Add support for additional attachment libraries.
230
+ * Add a more flexible replacement for the `to_name` shortcut.
231
+
232
+ ## Development
233
+
234
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `spec` to run the tests.
235
+
236
+ To release a new version of this gem, 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).
237
+
238
+ ## Contributing
239
+
240
+ Bug reports and pull requests are welcome on GitHub at https://github.com/CodeTectonics/decorator_dryer. 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/CodeTectonics/decorator_dryer/blob/master/CODE_OF_CONDUCT.md).
241
+
242
+ ## License
243
+
244
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
245
+
246
+ ## Code of Conduct
247
+
248
+ Everyone interacting in the DecoratorDryer project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/CodeTectonics/decorator_dryer/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 "rspec/core/rake_task"
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ require "rubocop/rake_task"
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: %i[spec rubocop]
data/bin/console ADDED
@@ -0,0 +1,11 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require "bundler/setup"
5
+ require "decorator_dryer"
6
+
7
+ # You can add fixtures and/or initialization code here to make experimenting
8
+ # with your gem easier. You can also use a different console, if you like.
9
+
10
+ require "irb"
11
+ IRB.start(__FILE__)
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,28 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "lib/decorator_dryer/version"
4
+
5
+ Gem::Specification.new do |s|
6
+ s.name = "decorator_dryer"
7
+ s.version = DecoratorDryer::VERSION
8
+ s.authors = ["Mark Harbison"]
9
+ s.email = ["mark@tyne-solutions.com"]
10
+
11
+ s.summary = "Shortcuts for concise view models."
12
+ s.description = "Shortcuts for concise view models."
13
+ s.homepage = "https://github.com/CodeTectonics/decorator_dryer"
14
+ s.license = "MIT"
15
+ s.required_ruby_version = ">= 2.6.0"
16
+
17
+ s.metadata["homepage_uri"] = s.homepage
18
+ s.metadata["source_code_uri"] = s.homepage
19
+ s.metadata["changelog_uri"] = "#{s.homepage}/blob/main/CHANGELOG.md"
20
+
21
+ s.files = `git ls-files`.split("\n")
22
+ s.test_files = `git ls-files -- spec/*`.split("\n")
23
+ s.require_paths = ["lib"]
24
+
25
+ s.add_development_dependency "rake", "~> 13.0"
26
+ s.add_development_dependency "rspec", "~> 3.12"
27
+ s.add_development_dependency "rubocop", "~> 1.7"
28
+ end
@@ -0,0 +1,77 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DecoratorDryer
4
+ module ActiveStorageShortcuts
5
+ def self.included(klass)
6
+ klass.extend(ClassMethods)
7
+ klass.include(Rails.application.routes.url_helpers)
8
+ end
9
+
10
+ module ClassMethods
11
+ def to_attachment(*attrs, preview_transform: nil)
12
+ to_attachment_url(*attrs)
13
+ to_attachment_name(*attrs)
14
+ to_attachment_preview(*attrs, transform: preview_transform)
15
+ to_attachment_signed_id(*attrs)
16
+ end
17
+
18
+ def to_attachment_url(*attrs)
19
+ attrs.each do |attr|
20
+ method_name = "#{attr}_url".to_sym
21
+
22
+ define_method(method_name) do
23
+ attachment = object.send(attr)
24
+
25
+ url_for(attachment) if attachment.attached?
26
+ end
27
+ end
28
+ end
29
+
30
+ def to_attachment_name(*attrs)
31
+ attrs.each do |attr|
32
+ method_name = "#{attr}_name".to_sym
33
+
34
+ define_method(method_name) do
35
+ attachment = object.send(attr)
36
+
37
+ attachment.blob.filename.as_json if attachment.attached?
38
+ end
39
+ end
40
+ end
41
+
42
+ def to_attachment_preview(*attrs, transform: nil)
43
+ transform ||= DecoratorDryer.configuration.attachment_shortcuts.default_preview_transform
44
+
45
+ attrs.each do |attr|
46
+ method_name = "#{attr}_preview".to_sym
47
+
48
+ define_method(method_name) do
49
+ return if transform.blank? || transform == :none
50
+
51
+ attachment = object.send(attr)
52
+ return unless attachment.attached?
53
+
54
+ if transform.is_a? Symbol
55
+ url_for attachment.variant(transform)
56
+ else
57
+ return unless attachment.representable?
58
+
59
+ url_for attachment.representation(transform).processed
60
+ end
61
+ end
62
+ end
63
+ end
64
+
65
+ def to_attachment_signed_id(*attrs)
66
+ attrs.each do |attr|
67
+ method_name = "#{attr}_signed_id".to_sym
68
+
69
+ define_method(method_name) do
70
+ attachment = object.send(attr)
71
+ attachment.signed_id if attachment.attached?
72
+ end
73
+ end
74
+ end
75
+ end
76
+ end
77
+ end
@@ -0,0 +1,30 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DecoratorDryer
4
+ class Configuration
5
+ attr_accessor :date_format, :humanized_date_format,
6
+ :datetime_format, :humanized_datetime_format, :time_format,
7
+ :extensions
8
+
9
+ attr_reader :attachment_shortcuts
10
+
11
+ def initialize
12
+ @date_format = "%Y-%m-%d"
13
+ @humanized_date_format = "%d/%m/%Y"
14
+ @datetime_format = "%Y-%m-%d %H:%M"
15
+ @humanized_datetime_format = "%H:%M %d/%m/%Y"
16
+ @time_format = "%H:%M"
17
+ @attachment_shortcuts = AttachmentShortcutsConfig.new
18
+ @extensions = []
19
+ end
20
+
21
+ class AttachmentShortcutsConfig
22
+ attr_accessor :mode, :default_preview_transform
23
+
24
+ def initialize
25
+ @mode = :none
26
+ @default_preview_transform = :none
27
+ end
28
+ end
29
+ end
30
+ end
@@ -0,0 +1,41 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DecoratorDryer
4
+ module Formatters
5
+ include ActionView::Helpers::NumberHelper
6
+
7
+ def format_date(date)
8
+ if context[:humanize]
9
+ date_format = DecoratorDryer.configuration.humanized_date_format
10
+ else
11
+ date_format = DecoratorDryer.configuration.date_format
12
+ end
13
+ date.try(:strftime, date_format)
14
+ end
15
+
16
+ def format_time(time)
17
+ time_format = DecoratorDryer.configuration.time_format
18
+ time.try(:strftime, time_format)
19
+ end
20
+
21
+ def format_datetime(datetime)
22
+ if context[:humanize]
23
+ datetime_format = DecoratorDryer.configuration.humanized_datetime_format
24
+ else
25
+ datetime_format = DecoratorDryer.configuration.datetime_format
26
+ end
27
+ datetime.try(:strftime, datetime_format)
28
+ end
29
+
30
+ def format_precision_number(number, precision = 0)
31
+ return 0.0 if number.blank?
32
+ return number.to_d if precision < 1
33
+
34
+ number_with_precision(number, precision: precision)
35
+ end
36
+
37
+ def to_name(association)
38
+ association.try(:name)
39
+ end
40
+ end
41
+ end
@@ -0,0 +1,55 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DecoratorDryer
4
+ module Shortcuts
5
+ include DecoratorDryer::Formatters
6
+
7
+ def self.included(klass)
8
+ klass.extend(ClassMethods)
9
+ end
10
+
11
+ module ClassMethods
12
+ def to_date_format(*attrs)
13
+ attrs.each do |attr|
14
+ define_method(attr) do
15
+ format_date object.send(attr)
16
+ end
17
+ end
18
+ end
19
+
20
+ def to_time_format(*attrs)
21
+ attrs.each do |attr|
22
+ define_method(attr) do
23
+ format_time object.send(attr)
24
+ end
25
+ end
26
+ end
27
+
28
+ def to_datetime_format(*attrs)
29
+ attrs.each do |attr|
30
+ define_method(attr) do
31
+ format_datetime object.send(attr)
32
+ end
33
+ end
34
+ end
35
+
36
+ def to_precision_number(*attrs, precision: 0)
37
+ attrs.each do |attr|
38
+ define_method(attr) do
39
+ format_precision_number object.send(attr), precision
40
+ end
41
+ end
42
+ end
43
+
44
+ def to_name(*attrs, suffix: "name")
45
+ attrs.each do |attr|
46
+ method_name = "#{attr}_#{suffix}".to_sym
47
+
48
+ define_method(method_name) do
49
+ to_name object.send(attr)
50
+ end
51
+ end
52
+ end
53
+ end
54
+ end
55
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DecoratorDryer
4
+ VERSION = "0.1.0"
5
+ end
@@ -0,0 +1,31 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "action_view"
4
+
5
+ require_relative "decorator_dryer/formatters"
6
+ require_relative "decorator_dryer/shortcuts"
7
+ require_relative "decorator_dryer/active_storage_shortcuts"
8
+ require_relative "decorator_dryer/configuration"
9
+
10
+ module DecoratorDryer
11
+ def self.included(klass)
12
+ klass.include(DecoratorDryer::Formatters)
13
+ klass.include(DecoratorDryer::Shortcuts)
14
+
15
+ if DecoratorDryer.configuration.attachment_shortcuts.mode == :active_storage
16
+ klass.include(DecoratorDryer::ActiveStorageShortcuts)
17
+ end
18
+
19
+ DecoratorDryer.configuration.extensions.each do |extension|
20
+ klass.include(extension)
21
+ end
22
+ end
23
+
24
+ def self.configuration
25
+ @configuration ||= DecoratorDryer::Configuration.new
26
+ end
27
+
28
+ def self.configure
29
+ yield DecoratorDryer.configuration
30
+ end
31
+ end
@@ -0,0 +1,4 @@
1
+ module DecoratorDryer
2
+ VERSION: String
3
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
4
+ end
@@ -0,0 +1,118 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "decorator_dryer"
4
+ require "dummy/dummy_model"
5
+ require "dummy/dummy_model_decorator"
6
+
7
+ RSpec.describe DecoratorDryer do
8
+ describe "::Formatters" do
9
+ it "returns formatted dates" do
10
+ decorator = DummyModelDecorator.new({})
11
+ result = decorator.format_date(Date.new(2023, 11, 1))
12
+ expect(result).to eq("2023-11-01")
13
+ end
14
+
15
+ it "returns humanized dates" do
16
+ decorator = DummyModelDecorator.new({}, { humanize: true })
17
+ result = decorator.format_date(Date.new(2023, 11, 1))
18
+ expect(result).to eq("01/11/2023")
19
+ end
20
+
21
+ it "returns formatted times" do
22
+ decorator = DummyModelDecorator.new({})
23
+ result = decorator.format_time(Time.new(2023, 11, 1, 11, 30, 0))
24
+ expect(result).to eq("11:30")
25
+ end
26
+
27
+ it "returns formatted datetimes" do
28
+ decorator = DummyModelDecorator.new({})
29
+ result = decorator.format_datetime(Time.new(2023, 11, 1, 11, 30, 0))
30
+ expect(result).to eq("2023-11-01 11:30")
31
+ end
32
+
33
+ it "returns humanized datetimes" do
34
+ decorator = DummyModelDecorator.new({}, { humanize: true })
35
+ result = decorator.format_datetime(Time.new(2023, 11, 1, 11, 30, 0))
36
+ expect(result).to eq("11:30 01/11/2023")
37
+ end
38
+
39
+ it "returns number with precision" do
40
+ decorator = DummyModelDecorator.new({})
41
+ result = decorator.format_precision_number(5, 3)
42
+ expect(result).to eq("5.000")
43
+ end
44
+
45
+ it "returns association names" do
46
+ decorator = DummyModelDecorator.new({})
47
+ association = DummyModel.new
48
+ association.name = "John Smith"
49
+ result = decorator.to_name(association)
50
+ expect(result).to eq("John Smith")
51
+ end
52
+ end
53
+
54
+ describe "::Shortcuts" do
55
+ let(:dummy_record) do
56
+ association1 = DummyModel.new
57
+ association1.name = "John Smith"
58
+
59
+ association2 = DummyModel.new
60
+ association2.name = "Joe Bloggs"
61
+
62
+ dummy_record = DummyModel.new
63
+ dummy_record.date1 = Date.new(2023, 11, 1)
64
+ dummy_record.date2 = Date.new(2023, 11, 2)
65
+ dummy_record.time1 = Time.new(2023, 11, 1, 11, 30, 0)
66
+ dummy_record.time2 = Time.new(2023, 11, 1, 12, 59, 0)
67
+ dummy_record.datetime1 = Time.new(2023, 11, 1, 13, 49, 0)
68
+ dummy_record.datetime2 = Time.new(2023, 11, 1, 15, 23, 0)
69
+ dummy_record.number1 = 5.321
70
+ dummy_record.number2 = 77.888888
71
+ dummy_record.association1 = association1
72
+ dummy_record.association2 = association2
73
+ dummy_record
74
+ end
75
+
76
+ it "returns formatted dates" do
77
+ decorator = DummyModelDecorator.new(dummy_record)
78
+ expect(decorator.date1).to eq("2023-11-01")
79
+ expect(decorator.date2).to eq("2023-11-02")
80
+ end
81
+
82
+ it "returns humanized dates" do
83
+ decorator = DummyModelDecorator.new(dummy_record, { humanize: true })
84
+ expect(decorator.date1).to eq("01/11/2023")
85
+ expect(decorator.date2).to eq("02/11/2023")
86
+ end
87
+
88
+ it "returns formatted times" do
89
+ decorator = DummyModelDecorator.new(dummy_record, { humanize: true })
90
+ expect(decorator.time1).to eq("11:30")
91
+ expect(decorator.time2).to eq("12:59")
92
+ end
93
+
94
+ it "returns formatted datetimes" do
95
+ decorator = DummyModelDecorator.new(dummy_record)
96
+ expect(decorator.datetime1).to eq("2023-11-01 13:49")
97
+ expect(decorator.datetime2).to eq("2023-11-01 15:23")
98
+ end
99
+
100
+ it "returns humanized datetimes" do
101
+ decorator = DummyModelDecorator.new(dummy_record, { humanize: true })
102
+ expect(decorator.datetime1).to eq("13:49 01/11/2023")
103
+ expect(decorator.datetime2).to eq("15:23 01/11/2023")
104
+ end
105
+
106
+ it "returns number with precision" do
107
+ decorator = DummyModelDecorator.new(dummy_record)
108
+ expect(decorator.number1).to eq("5.32")
109
+ expect(decorator.number2).to eq("77.89")
110
+ end
111
+
112
+ it "returns association names" do
113
+ decorator = DummyModelDecorator.new(dummy_record)
114
+ expect(decorator.association1_name).to eq("John Smith")
115
+ expect(decorator.association2_name).to eq("Joe Bloggs")
116
+ end
117
+ end
118
+ end
@@ -0,0 +1,6 @@
1
+ # frozen_string_literal: true
2
+
3
+ class DummyModel
4
+ attr_accessor :date1, :date2, :time1, :time2, :datetime1, :datetime2, :number1, :number2,
5
+ :association1, :association2, :name
6
+ end
@@ -0,0 +1,18 @@
1
+ # frozen_string_literal: true
2
+
3
+ class DummyModelDecorator
4
+ include DecoratorDryer
5
+
6
+ attr_accessor :object, :context
7
+
8
+ to_date_format :date1, :date2
9
+ to_time_format :time1, :time2
10
+ to_datetime_format :datetime1, :datetime2
11
+ to_precision_number :number1, :number2, precision: 2
12
+ to_name :association1, :association2
13
+
14
+ def initialize(object, context = {})
15
+ self.object = object
16
+ self.context = context
17
+ end
18
+ end
@@ -0,0 +1,98 @@
1
+ # frozen_string_literal: true
2
+
3
+ # This file was generated by the `rspec --init` command. Conventionally, all
4
+ # specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`.
5
+ # The generated `.rspec` file contains `--require spec_helper` which will cause
6
+ # this file to always be loaded, without a need to explicitly require it in any
7
+ # files.
8
+ #
9
+ # Given that it is always loaded, you are encouraged to keep this file as
10
+ # light-weight as possible. Requiring heavyweight dependencies from this file
11
+ # will add to the boot time of your test suite on EVERY test run, even for an
12
+ # individual file that may not need all of that loaded. Instead, consider making
13
+ # a separate helper file that requires the additional dependencies and performs
14
+ # the additional setup, and require it from the spec files that actually need
15
+ # it.
16
+ #
17
+ # See https://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
18
+ RSpec.configure do |config|
19
+ # rspec-expectations config goes here. You can use an alternate
20
+ # assertion/expectation library such as wrong or the stdlib/minitest
21
+ # assertions if you prefer.
22
+ config.expect_with :rspec do |expectations|
23
+ # This option will default to `true` in RSpec 4. It makes the `description`
24
+ # and `failure_message` of custom matchers include text for helper methods
25
+ # defined using `chain`, e.g.:
26
+ # be_bigger_than(2).and_smaller_than(4).description
27
+ # # => "be bigger than 2 and smaller than 4"
28
+ # ...rather than:
29
+ # # => "be bigger than 2"
30
+ expectations.include_chain_clauses_in_custom_matcher_descriptions = true
31
+ end
32
+
33
+ # rspec-mocks config goes here. You can use an alternate test double
34
+ # library (such as bogus or mocha) by changing the `mock_with` option here.
35
+ config.mock_with :rspec do |mocks|
36
+ # Prevents you from mocking or stubbing a method that does not exist on
37
+ # a real object. This is generally recommended, and will default to
38
+ # `true` in RSpec 4.
39
+ mocks.verify_partial_doubles = true
40
+ end
41
+
42
+ # This option will default to `:apply_to_host_groups` in RSpec 4 (and will
43
+ # have no way to turn it off -- the option exists only for backwards
44
+ # compatibility in RSpec 3). It causes shared context metadata to be
45
+ # inherited by the metadata hash of host groups and examples, rather than
46
+ # triggering implicit auto-inclusion in groups with matching metadata.
47
+ config.shared_context_metadata_behavior = :apply_to_host_groups
48
+
49
+ # The settings below are suggested to provide a good initial experience
50
+ # with RSpec, but feel free to customize to your heart's content.
51
+ # # This allows you to limit a spec run to individual examples or groups
52
+ # # you care about by tagging them with `:focus` metadata. When nothing
53
+ # # is tagged with `:focus`, all examples get run. RSpec also provides
54
+ # # aliases for `it`, `describe`, and `context` that include `:focus`
55
+ # # metadata: `fit`, `fdescribe` and `fcontext`, respectively.
56
+ # config.filter_run_when_matching :focus
57
+ #
58
+ # # Allows RSpec to persist some state between runs in order to support
59
+ # # the `--only-failures` and `--next-failure` CLI options. We recommend
60
+ # # you configure your source control system to ignore this file.
61
+ # config.example_status_persistence_file_path = "spec/examples.txt"
62
+ #
63
+ # # Limits the available syntax to the non-monkey patched syntax that is
64
+ # # recommended. For more details, see:
65
+ # # https://rspec.info/features/3-12/rspec-core/configuration/zero-monkey-patching-mode/
66
+ # config.disable_monkey_patching!
67
+ #
68
+ # # This setting enables warnings. It's recommended, but in some cases may
69
+ # # be too noisy due to issues in dependencies.
70
+ # config.warnings = true
71
+ #
72
+ # # Many RSpec users commonly either run the entire suite or an individual
73
+ # # file, and it's useful to allow more verbose output when running an
74
+ # # individual spec file.
75
+ # if config.files_to_run.one?
76
+ # # Use the documentation formatter for detailed output,
77
+ # # unless a formatter has already been configured
78
+ # # (e.g. via a command-line flag).
79
+ # config.default_formatter = "doc"
80
+ # end
81
+ #
82
+ # # Print the 10 slowest examples and example groups at the
83
+ # # end of the spec run, to help surface which specs are running
84
+ # # particularly slow.
85
+ # config.profile_examples = 10
86
+ #
87
+ # # Run specs in random order to surface order dependencies. If you find an
88
+ # # order dependency and want to debug it, you can fix the order by providing
89
+ # # the seed, which is printed after each run.
90
+ # # --seed 1234
91
+ # config.order = :random
92
+ #
93
+ # # Seed global randomization in this process using the `--seed` CLI option.
94
+ # # Setting this allows you to use `--seed` to deterministically reproduce
95
+ # # test failures related to randomization by passing the same `--seed` value
96
+ # # as the one that triggered the failure.
97
+ # Kernel.srand config.seed
98
+ end
metadata ADDED
@@ -0,0 +1,116 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: decorator_dryer
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Mark Harbison
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2024-01-01 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: rake
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '13.0'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '13.0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rspec
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '3.12'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '3.12'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rubocop
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '1.7'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '1.7'
55
+ description: Shortcuts for concise view models.
56
+ email:
57
+ - mark@tyne-solutions.com
58
+ executables: []
59
+ extensions: []
60
+ extra_rdoc_files: []
61
+ files:
62
+ - ".gitignore"
63
+ - ".rspec"
64
+ - ".rubocop.yml"
65
+ - CHANGELOG.md
66
+ - CODE_OF_CONDUCT.md
67
+ - Gemfile
68
+ - Gemfile.lock
69
+ - LICENSE.txt
70
+ - README.md
71
+ - Rakefile
72
+ - bin/console
73
+ - bin/setup
74
+ - decorator_dryer.gemspec
75
+ - lib/decorator_dryer.rb
76
+ - lib/decorator_dryer/active_storage_shortcuts.rb
77
+ - lib/decorator_dryer/configuration.rb
78
+ - lib/decorator_dryer/formatters.rb
79
+ - lib/decorator_dryer/shortcuts.rb
80
+ - lib/decorator_dryer/version.rb
81
+ - sig/decorator_dryer.rbs
82
+ - spec/decorator_dryer_spec.rb
83
+ - spec/dummy/dummy_model.rb
84
+ - spec/dummy/dummy_model_decorator.rb
85
+ - spec/spec_helper.rb
86
+ homepage: https://github.com/CodeTectonics/decorator_dryer
87
+ licenses:
88
+ - MIT
89
+ metadata:
90
+ homepage_uri: https://github.com/CodeTectonics/decorator_dryer
91
+ source_code_uri: https://github.com/CodeTectonics/decorator_dryer
92
+ changelog_uri: https://github.com/CodeTectonics/decorator_dryer/blob/main/CHANGELOG.md
93
+ post_install_message:
94
+ rdoc_options: []
95
+ require_paths:
96
+ - lib
97
+ required_ruby_version: !ruby/object:Gem::Requirement
98
+ requirements:
99
+ - - ">="
100
+ - !ruby/object:Gem::Version
101
+ version: 2.6.0
102
+ required_rubygems_version: !ruby/object:Gem::Requirement
103
+ requirements:
104
+ - - ">="
105
+ - !ruby/object:Gem::Version
106
+ version: '0'
107
+ requirements: []
108
+ rubygems_version: 3.4.21
109
+ signing_key:
110
+ specification_version: 4
111
+ summary: Shortcuts for concise view models.
112
+ test_files:
113
+ - spec/decorator_dryer_spec.rb
114
+ - spec/dummy/dummy_model.rb
115
+ - spec/dummy/dummy_model_decorator.rb
116
+ - spec/spec_helper.rb