dekorator 1.0.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: e632f3f499971f15713b16354a960d3c0c2e42436694a040d5a77c8627baec7a
4
+ data.tar.gz: 1318630635b3406f2336d0d144d1651c0b66bb013e4f5e342c726314ba145b30
5
+ SHA512:
6
+ metadata.gz: c51f4aa3459a64007d77e6f33361e2fdacceb56893f05cfef773c2bd0401ea92cb021bd6fc8153ff8b679fcff52de642fe7338d8cefe448b59595edc36e1ed19
7
+ data.tar.gz: 453e6c9a109f4b0c791a211365284adac236496dd7e7f7280103066f074e867c103f9d1c298b5096f3228e9bc4627f73713da659c38e62e5e20af5b0eaa74909
@@ -0,0 +1,51 @@
1
+ name: Tests
2
+
3
+ on: [push, pull_request]
4
+
5
+ jobs:
6
+ test:
7
+ name: Ruby ${{ matrix.versions.ruby }}, Rails ${{ matrix.versions.rails }}
8
+ runs-on: ubuntu-latest
9
+ strategy:
10
+ matrix:
11
+ versions:
12
+ - { ruby: "2.4.x", rails: "5.0.x" }
13
+ - { ruby: "2.5.x", rails: "5.0.x" }
14
+ - { ruby: "2.6.x", rails: "5.0.x" }
15
+ - { ruby: "2.4.x", rails: "5.1.x" }
16
+ - { ruby: "2.5.x", rails: "5.1.x" }
17
+ - { ruby: "2.6.x", rails: "5.1.x" }
18
+ - { ruby: "2.4.x", rails: "5.2.x" }
19
+ - { ruby: "2.5.x", rails: "5.2.x" }
20
+ - { ruby: "2.6.x", rails: "5.2.x" }
21
+ - { ruby: "2.5.x", rails: "6.0.x" }
22
+ - { ruby: "2.6.x", rails: "6.0.x" }
23
+
24
+ steps:
25
+ - uses: actions/checkout@v1
26
+
27
+ - uses: actions/cache@v1
28
+ id: cache
29
+ with:
30
+ path: gemfiles/vendor/bundle
31
+ key: ruby-${{ matrix.versions.ruby }}-rails-${{ matrix.versions.rails }}
32
+
33
+ - name: Set up Ruby
34
+ uses: actions/setup-ruby@v1
35
+ with:
36
+ ruby-version: ${{ matrix.versions.ruby }}
37
+
38
+ - name: Set up bundler
39
+ run: |
40
+ echo 'gem: --no-document' >> ~/.gemrc
41
+ gem install bundler
42
+ bundle config --global gemfile gemfiles/rails_${{ matrix.versions.rails }}.gemfile
43
+ bundle config --global path vendor/bundle
44
+
45
+ - name: Install gems
46
+ run: |
47
+ bundle install --jobs $(nproc) --retry 3
48
+
49
+ - name: Test with Rake
50
+ run: |
51
+ bundle exec rake test:all_with_coverage
@@ -0,0 +1,32 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [Unreleased]
9
+ Nothing yet
10
+
11
+ ## [1.0.0] - 2019-12-02
12
+ ### Added
13
+ - Avoid deep decoration ([#25](https://github.com/komposable/dekorator/pull/25))
14
+ - Make `decorate` accessible in ApplicationController ([#29](https://github.com/komposable/dekorator/pull/29))
15
+
16
+ ### Changed
17
+ - Moved to Komposable organization ([#13](https://github.com/komposable/dekorator/pull/13))
18
+ - Replace Travis CI by Github Actions and remove ruby 2.3 support ([#23](https://github.com/komposable/dekorator/pull/23))
19
+ - Update railtie to prevent triggering initialization autoloaded constant deprecation warning ([#30](https://github.com/komposable/dekorator/pull/30))
20
+ - Improve generators ([#31](https://github.com/komposable/dekorator/pull/31))
21
+
22
+ ### Fixes
23
+ - Fix DecoratedEnumerableProxy for Rails 6 ([5a656333](https://github.com/komposable/dekorator/commit/5a656333e9ca6321d0474f0e54de4332219b88d0))
24
+
25
+ ## 1.0.0.pre.1 - 2019-01-30
26
+ ### Added
27
+ - Create Dekorator::Base the base of decorators ([a2a36d66](https://github.com/komposable/dekorator/commit/a2a36d66c6de6cb0a00f783794cd29f899bc04b6))
28
+ - Create `dekorator:install` generator ([a2a36d66](https://github.com/komposable/dekorator/commit/a2a36d66c6de6cb0a00f783794cd29f899bc04b6))
29
+ - Create `decorator` generator ([a2a36d66](https://github.com/komposable/dekorator/commit/a2a36d66c6de6cb0a00f783794cd29f899bc04b6))
30
+
31
+ [Unreleased]: https://github.com/komposable/dekorator/compare/v1.0.0...master
32
+ [1.0.0]: https://github.com/komposable/dekorator/compare/v1.0.0...1.0.0.pre.1
@@ -0,0 +1,74 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ In the interest of fostering an open and welcoming environment, we as
6
+ contributors and maintainers pledge to making participation in our project and
7
+ our community a harassment-free experience for everyone, regardless of age, body
8
+ size, disability, ethnicity, gender identity and expression, level of experience,
9
+ nationality, personal appearance, race, religion, or sexual identity and
10
+ orientation.
11
+
12
+ ## Our Standards
13
+
14
+ Examples of behavior that contributes to creating a positive environment
15
+ include:
16
+
17
+ * Using welcoming and inclusive language
18
+ * Being respectful of differing viewpoints and experiences
19
+ * Gracefully accepting constructive criticism
20
+ * Focusing on what is best for the community
21
+ * Showing empathy towards other community members
22
+
23
+ Examples of unacceptable behavior by participants include:
24
+
25
+ * The use of sexualized language or imagery and unwelcome sexual attention or
26
+ advances
27
+ * Trolling, insulting/derogatory comments, and personal or political attacks
28
+ * Public or private harassment
29
+ * Publishing others' private information, such as a physical or electronic
30
+ address, without explicit permission
31
+ * Other conduct which could reasonably be considered inappropriate in a
32
+ professional setting
33
+
34
+ ## Our Responsibilities
35
+
36
+ Project maintainers are responsible for clarifying the standards of acceptable
37
+ behavior and are expected to take appropriate and fair corrective action in
38
+ response to any instances of unacceptable behavior.
39
+
40
+ Project maintainers have the right and responsibility to remove, edit, or
41
+ reject comments, commits, code, wiki edits, issues, and other contributions
42
+ that are not aligned to this Code of Conduct, or to ban temporarily or
43
+ permanently any contributor for other behaviors that they deem inappropriate,
44
+ threatening, offensive, or harmful.
45
+
46
+ ## Scope
47
+
48
+ This Code of Conduct applies both within project spaces and in public spaces
49
+ when an individual is representing the project or its community. Examples of
50
+ representing a project or community include using an official project e-mail
51
+ address, posting via an official social media account, or acting as an appointed
52
+ representative at an online or offline event. Representation of a project may be
53
+ further defined and clarified by project maintainers.
54
+
55
+ ## Enforcement
56
+
57
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
58
+ reported by contacting the project team at oss@pantographe.studio. All
59
+ complaints will be reviewed and investigated and will result in a response that
60
+ is deemed necessary and appropriate to the circumstances. The project team is
61
+ obligated to maintain confidentiality with regard to the reporter of an incident.
62
+ Further details of specific enforcement policies may be posted separately.
63
+
64
+ Project maintainers who do not follow or enforce the Code of Conduct in good
65
+ faith may face temporary or permanent repercussions as determined by other
66
+ members of the project's leadership.
67
+
68
+ ## Attribution
69
+
70
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71
+ available at [http://contributor-covenant.org/version/1/4][version]
72
+
73
+ [homepage]: http://contributor-covenant.org
74
+ [version]: http://contributor-covenant.org/version/1/4/
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2019 Pantographe
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.
@@ -0,0 +1,245 @@
1
+ # Dekorator
2
+
3
+ [![Tests](https://github.com/komposable/dekorator/workflows/Tests/badge.svg)](https://github.com/komposable/dekorator/actions)
4
+ [![Gem Version](https://badge.fury.io/rb/dekorator.svg)](https://rubygems.org/gems/dekorator)
5
+ [![Maintainability](https://api.codeclimate.com/v1/badges/f7ab08512ead00da34c0/maintainability)](https://codeclimate.com/github/komposable/dekorator/maintainability)
6
+ [![Coverage Status](https://coveralls.io/repos/github/komposable/dekorator/badge.svg)](https://coveralls.io/github/komposable/dekorator)
7
+ [![Inch CI](https://inch-ci.org/github/komposable/dekorator.svg?branch=master)](https://inch-ci.org/github/komposable/dekorator)
8
+ [![Yardoc](https://img.shields.io/badge/doc-yardoc-blue.svg)](https://www.rubydoc.info/github/komposable/dekorator/master)
9
+
10
+ **Dekorator** is a lightweight library to implement _presenters_ and/or _decorators_ in your Rails app. It has less features than [`draper`](https://github.com/drapergem/draper) and aims at having a lower memory footprint.
11
+
12
+ This gem has been inspired by our Rails development practices at [Pantographe](https://pantographe.studio), and the [Ruby memory, ActiveRecord and Draper](https://medium.com/appaloosa-store-engineering/ruby-memory-activerecord-and-draper-64f06abeeb34) talk by [Benoit Tigeot](https://github.com/benoittgt).
13
+
14
+ ## Compatibility
15
+
16
+ * Ruby 2.4+
17
+ * Rails 5.0+
18
+
19
+ ## Installation
20
+
21
+ Add this line to your application `Gemfile`:
22
+
23
+ ```ruby
24
+ gem "dekorator"
25
+ ```
26
+
27
+ And then execute:
28
+
29
+ $ bundle
30
+
31
+ ## Getting started
32
+
33
+ Run the following command to set up your project:
34
+
35
+ $ rails generate dekorator:install
36
+
37
+ This command will create an `ApplicationDecorator` file.
38
+
39
+ ## Usage
40
+
41
+ Generate a new decorator with the `decorator` generator:
42
+
43
+ $ rails generate decorator user
44
+
45
+ This command will generate the following file:
46
+
47
+ ```ruby
48
+ class UserDecorator < ApplicationDecorator
49
+ include ActionView::Helpers::TextHelper
50
+
51
+ decorates_association :posts
52
+
53
+ def full_name
54
+ [first_name, last_name].join(" ")
55
+ end
56
+
57
+ def biography_summary
58
+ truncate(biography, length: 170)
59
+ end
60
+ end
61
+ ```
62
+
63
+ ### Decorate from a controller
64
+
65
+ ```ruby
66
+ class UsersController < ApplicationController
67
+ def index
68
+ @users = decorate User.all
69
+ end
70
+
71
+ def show
72
+ @user = decorate User.find(params[:id])
73
+ end
74
+ end
75
+ ```
76
+
77
+ ### Decorate from a view
78
+
79
+ ```erb
80
+ # app/views/users/index.html.erb
81
+
82
+ <ul>
83
+ <% decorate(@users).each do |user| %>
84
+ <li><%= user.full_name %></li>
85
+ <% end %>
86
+ </ul>
87
+ ```
88
+
89
+ ### Decorate outside a controller/view
90
+
91
+ ```ruby
92
+ UserDecorate.decorate(User.first) # => UserDecorator
93
+ ```
94
+
95
+ ### Associations
96
+
97
+ If you want to automatically decorate an association for a decorated object,
98
+ you have to use `#decorates_association` as following:
99
+
100
+ ```ruby
101
+ class UserDecorator < ApplicationDecorator
102
+ decorates_association :posts
103
+
104
+ ...
105
+ end
106
+
107
+ class PostDecorator < ApplicationDecorator
108
+ ...
109
+ end
110
+ ```
111
+
112
+ In this example, `UserDecorator#posts` will be decorated.
113
+
114
+ ```ruby
115
+ decorated_user = decorate(User.first)
116
+ decorated_user # => UserDecorator
117
+ decorated_user.posts.first # => PostDecorator
118
+ ```
119
+
120
+ ### Custom decorator
121
+
122
+ By default, Dekorator searches for the decorator class by adding `Decorator` at the end.
123
+ For `User`, Dekorator looks for the `UserDecorator` class, and for `User::Profile`
124
+ it looks for `User::ProfileDecorator`.
125
+
126
+ If you want to create a specific decorator or sub-decorator, you can simply
127
+ specify the decorator class that should be used.
128
+
129
+ ```ruby
130
+ class AdminDecorator < ApplicationDecorator
131
+ ...
132
+ end
133
+
134
+ decorated_user = decorate(User.first, with: AdminDecorator)
135
+ decorated_user # => AdminDecorator
136
+ ```
137
+
138
+ You can also specify the decorator for associations:
139
+
140
+ ```ruby
141
+ class UserDecorator < ApplicationDecorator
142
+ decorates_association :posts, with: ArticleDecorator
143
+
144
+ ...
145
+ end
146
+
147
+ class ArticleDecorator < ApplicationDecorator
148
+ end
149
+
150
+ decorated_user = decorate(User.first)
151
+ decorated_user # => UserDecorator
152
+ decorated_user.posts.first # => ArticleDecorator
153
+ ```
154
+
155
+ ## Compatibility
156
+
157
+ ### ActiveAdmin
158
+
159
+ This gem is compatible with [`activeadmin`][activeadmin].
160
+
161
+ Simply use `#decorate_with`
162
+
163
+ ```ruby
164
+ # app/admin/post.rb
165
+ ActiveAdmin.register Post do
166
+ decorate_with PostDecorator
167
+
168
+ index do
169
+ column :title
170
+ column :image
171
+ actions
172
+ end
173
+ end
174
+ ```
175
+
176
+ ### Devise
177
+
178
+ If you use the [`Devise`][devise] gem you may have an issue if you decorate your
179
+ `User` model.
180
+
181
+ You must define `#devise_scope` as following. Devise needs to manage with the
182
+ `User` model (https://github.com/plataformatec/devise/blob/369ba267efaa10d01c8dba59b09c3b94dd9e5551/lib/devise/mapping.rb#L35).
183
+
184
+ ```ruby
185
+ class UserDecorator < ApplicationDecorator
186
+ ...
187
+
188
+ def devise_scope
189
+ __getobj__
190
+ end
191
+ end
192
+ ```
193
+
194
+ ## Testing
195
+
196
+ `rails generate decorator user` also generates a testing file based on your
197
+ configuration.
198
+
199
+ You can test a decorator the same way you do for helpers.
200
+
201
+ ### RSpec
202
+
203
+ ```ruby
204
+ describe UserDecorator, type: :decorator do
205
+ let(:object) { User.new(first_name: "John", last_name: "Doe") }
206
+ let(:decorated_user) { described_class.new(object) }
207
+
208
+ describe "#full_name" do
209
+ it { expect(decorated_user.full_name).to eq("John Doe") }
210
+ end
211
+ end
212
+ ```
213
+
214
+ ## Development
215
+
216
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run
217
+ `rake spec` to run the tests. You can also run `bin/console` for an interactive
218
+ prompt that will allow you to experiment.
219
+
220
+ To install this gem onto your local machine, run `bundle exec rake install`.
221
+ To release a new version, update the version number in `version.rb`, then
222
+ run `bundle exec rake release`, which will create a git tag for the version,
223
+ push git commits and tags, and push the `.gem` file to [rubygems.org].
224
+
225
+ ## Contributing
226
+
227
+ Bug reports and pull requests are welcome on GitHub at
228
+ https://github.com/komposable/dekorator. This project is intended to be a safe,
229
+ welcoming space for collaboration, and contributors are expected to adhere to
230
+ the [Contributor Covenant](http://contributor-covenant.org) code of conduct.
231
+
232
+ ## License
233
+
234
+ The gem is available as open source under the terms of the [MIT License].
235
+
236
+ ## Code of Conduct
237
+
238
+ Everyone interacting in the Dekorator project codebases, issue trackers,
239
+ chat rooms and mailing lists is expected to follow the [code of conduct].
240
+
241
+ [activeadmin]: https://activeadmin.info/11-decorators.html
242
+ [devise]: https://github.com/plataformatec/devise/
243
+ [rubygems.org]: https://rubygems.org
244
+ [MIT License]: https://opensource.org/licenses/MIT
245
+ [code of conduct]: https://github.com/komposable/dekorator/blob/master/CODE_OF_CONDUCT.md
@@ -0,0 +1,21 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rubocop/rake_task"
5
+ require "rspec/core/rake_task"
6
+ require "coveralls/rake/task"
7
+
8
+ namespace :test do
9
+ task all: %i[rubocop spec]
10
+ task all_with_coverage: %i[all coveralls:push]
11
+
12
+ RuboCop::RakeTask.new
13
+
14
+ RSpec::Core::RakeTask.new(:spec)
15
+
16
+ Coveralls::RakeTask.new
17
+ end
18
+
19
+ task test: :"test:all"
20
+
21
+ task default: :test
@@ -0,0 +1,7 @@
1
+ # Benchmarks
2
+
3
+ ## Run benchmarks
4
+
5
+ ```sh
6
+ $ ruby benchmark.rb
7
+ ```
@@ -0,0 +1,135 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/inline"
4
+
5
+ gemfile(true) do
6
+ source "https://rubygems.org"
7
+
8
+ git_source(:github) { |repo| "https://github.com/#{repo}.git" }
9
+
10
+ gem "rails", "6.0.1"
11
+ gem "sqlite3"
12
+ gem "benchmark-ips"
13
+ gem "benchmark-memory"
14
+
15
+ gem "dekorator", path: "../", require: false
16
+ gem "draper", require: false
17
+ end
18
+
19
+ require "active_record"
20
+ require "logger"
21
+
22
+ ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:")
23
+ ActiveRecord::Base.logger = nil # Logger.new(STDOUT)
24
+
25
+ ActiveRecord::Schema.define do
26
+ create_table :posts, force: true do |t|
27
+ t.string :title
28
+ t.text :body
29
+ end
30
+
31
+ create_table :comments, force: true do |t|
32
+ t.integer :post_id
33
+ t.string :author
34
+ t.text :body
35
+ end
36
+ end
37
+
38
+ # Models
39
+ class Post < ActiveRecord::Base
40
+ has_many :comments
41
+
42
+ def summary
43
+ @summary ||= body&.truncate(170)
44
+ end
45
+ end
46
+
47
+ class Comment < ActiveRecord::Base
48
+ belongs_to :post
49
+ end
50
+
51
+ # Data
52
+ comments = 100.times.map { Comment.new(author: "John D.", body: "Great article") }
53
+ 10.times.each { Post.create!(title: "Our first article!", body: "", comments: comments) }
54
+
55
+ # Decorators
56
+ require "dekorator"
57
+
58
+ class PostDecorator < Dekorator::Base
59
+ decorates_association :comments
60
+
61
+ def summary
62
+ @summary ||= body&.truncate(170)
63
+ end
64
+ end
65
+
66
+ class CommentDecorator < Dekorator::Base
67
+ end
68
+
69
+ require "draper"
70
+
71
+ class CommentDraperDecorator < Draper::Decorator
72
+ end
73
+
74
+ class PostDraperDecorator < Draper::Decorator
75
+ decorates_association :comments, with: CommentDraperDecorator
76
+
77
+ def summary
78
+ @summary ||= object.body&.truncate(170)
79
+ end
80
+ end
81
+
82
+ require "delegate"
83
+
84
+ class PostDelegator < SimpleDelegator
85
+ def summary
86
+ @summary ||= body&.truncate(170)
87
+ end
88
+
89
+ def comments
90
+ @comments = __getobj__.comments.map { |comment| CommentDelegator.new(CommentDelegator) }
91
+ end
92
+ end
93
+
94
+ class CommentDelegator < SimpleDelegator
95
+ end
96
+
97
+ # Benchmark
98
+ SCENARIOS = {
99
+ "#summary" => :summary,
100
+ "#comments" => :comments,
101
+ }
102
+
103
+ SCENARIOS.each_pair do |name, method|
104
+ puts
105
+ puts " #{name} ".center(80, "=")
106
+ puts
107
+
108
+ model = Post.all
109
+
110
+ puts " ips ".center(80, "-")
111
+ puts
112
+
113
+ Benchmark.ips do |x|
114
+ x.report("In model") { model.first.public_send(method) }
115
+ x.report("Dekorator") { PostDecorator.decorate(model).first.public_send(method) }
116
+ x.report("Dekorator.new") { PostDecorator.decorate(model).first.public_send(method) }
117
+ x.report("Draper") { PostDraperDecorator.decorate_collection(model).first.public_send(method) }
118
+ x.report("SimpleDelegator") { PostDelegator.new(model.first).public_send(method) }
119
+
120
+ x.compare!
121
+ end
122
+
123
+ puts " memory ".center(80, "-")
124
+ puts
125
+
126
+ Benchmark.memory do |x|
127
+ x.report("In model") { model.first.public_send(method) }
128
+ x.report("Dekorator") { PostDecorator.decorate(model).first.public_send(method) }
129
+ x.report("Dekorator.new") { PostDecorator.decorate(model).first.public_send(method) }
130
+ x.report("Draper") { PostDraperDecorator.decorate_collection(model).first.public_send(method) }
131
+ x.report("SimpleDelegator") { PostDelegator.new(model.first).public_send(method) }
132
+
133
+ x.compare!
134
+ end
135
+ end
@@ -0,0 +1,47 @@
1
+ # frozen_string_literal: true
2
+
3
+ lib = File.expand_path("lib", __dir__)
4
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
5
+ require "dekorator/version"
6
+
7
+ Gem::Specification.new do |spec|
8
+ spec.name = "dekorator"
9
+ spec.version = Dekorator::VERSION
10
+ spec.authors = ["Pantographe"]
11
+ spec.email = ["oss@pantographe.studio"]
12
+
13
+ spec.summary = "An opinionated way of organizing model-view code in Ruby on Rails, based on decorators"
14
+ spec.description = "An opinionated way of organizing model-view code in Ruby on Rails, based on decorators"
15
+ spec.homepage = "http://komponent.io"
16
+ spec.license = "MIT"
17
+
18
+ spec.metadata = {
19
+ "homepage_uri" => "https://github.com/komposable/dekorator",
20
+ "changelog_uri" => "https://github.com/komposable/dekorator/blob/master/CHANGELOG.md",
21
+ "source_code_uri" => "https://github.com/komposable/dekorator",
22
+ "bug_tracker_uri" => "https://github.com/komposable/dekorator/issues",
23
+ }
24
+
25
+ # Specify which files should be added to the gem when it is released.
26
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
27
+ spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do
28
+ `git ls-files -z`.split("\x0")
29
+ .reject do |f|
30
+ f.match(%r{^(test|spec|features|gemfiles|bin)/}) \
31
+ || %w[.editorconfig .gitignore .inch.yml .rspec .rubocop.yml .simplecov .travis.yml
32
+ .yardots Appraisals Gemfile Gemfile.lock].include?(f)
33
+ end
34
+ end
35
+
36
+ spec.require_paths = ["lib"]
37
+
38
+ spec.required_ruby_version = ">= 2.3"
39
+
40
+ spec.add_runtime_dependency "actionview", ">= 5.0", "< 6.1"
41
+ spec.add_runtime_dependency "activesupport", ">= 5.0", "< 6.1"
42
+ spec.add_runtime_dependency "railties", ">= 5.0", "< 6.1"
43
+
44
+ spec.add_development_dependency "bundler", "~> 2.0"
45
+ spec.add_development_dependency "rake", "~> 10.0"
46
+ spec.add_development_dependency "rspec", "~> 3.0"
47
+ end
@@ -0,0 +1,151 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "dekorator/version"
4
+ require "delegate"
5
+
6
+ # :nodoc
7
+ module Dekorator
8
+ # @api private
9
+ module Generators; end
10
+
11
+ class DecoratorNotFound < ArgumentError; end
12
+
13
+ # Base decorator.
14
+ class Base < SimpleDelegator
15
+ class << self
16
+ # Decorate an object with a decorator.
17
+ #
18
+ # @param object_or_collection [Object, Enumerable] the object or collection to decorate.
19
+ # @option opts [Class] :with the decorator class to use. If empty a decorator will be guessed.
20
+ #
21
+ # @return [Dekorator::Base, ActiveRecord::Relation, Enumerable] the obect or collection decorated.
22
+ #
23
+ # @raise [DecoratorNotFound] if decorator is not found.
24
+ def decorate(object_or_collection, with: nil)
25
+ return object_or_collection if decorable_object?(object_or_collection)
26
+
27
+ with ||= self if with != :__guess__ && self != Dekorator::Base
28
+ with = _guess_decorator(object_or_collection) if with.nil? || with == :__guess__
29
+
30
+ object_or_collection = _decorate(object_or_collection, with: with)
31
+
32
+ if block_given?
33
+ yield object_or_collection
34
+ else
35
+ object_or_collection
36
+ end
37
+ end
38
+
39
+ # Define that an association must be decorated.
40
+ #
41
+ # @param relation_name [String, Symbol] the association name to decorate.
42
+ # @option opts [Class] :with the decorator class to use. If empty a decorator will be guessed.
43
+ #
44
+ # @example Define an association to decorate
45
+ # class UserDecorator < Dekorator::Base
46
+ # decorates_association :posts
47
+ # end
48
+ #
49
+ # # A decorator could be precise
50
+ # class UserDecorator < Dekorator::Base
51
+ # decorates_association :posts, PostDecorator
52
+ # end
53
+ def decorates_association(relation_name, with: :__guess__)
54
+ relation_name = relation_name.to_sym
55
+
56
+ define_method(relation_name) do
57
+ @decorated_associations[relation_name] ||= decorate(__getobj__.public_send(relation_name), with: with)
58
+ end
59
+ end
60
+
61
+ # Guess and returns the decorated object class.
62
+ #
63
+ # @return [Class] the decorated object class.
64
+ def base_class
65
+ _safe_constantize(name.gsub("Decorator", ""))
66
+ end
67
+
68
+ private
69
+
70
+ def _decorate(object_or_enumerable, with:)
71
+ if !object_or_enumerable.is_a? Enumerable
72
+ with.new(object_or_enumerable)
73
+ else
74
+ if defined?(ActiveRecord::Relation) && object_or_enumerable.is_a?(ActiveRecord::Relation)
75
+ Dekorator::DecoratedEnumerableProxy.new(with, object_or_enumerable)
76
+ else object_or_enumerable.is_a? Enumerable
77
+ object_or_enumerable.map { |object| _decorate(object, with: with) }
78
+ end
79
+ end
80
+ end
81
+
82
+ def _guess_decorator(object_or_enumerable)
83
+ object_or_enumerable = object_or_enumerable.first if object_or_enumerable.is_a? Enumerable
84
+
85
+ _safe_constantize("#{object_or_enumerable.class}Decorator") \
86
+ || raise(DecoratorNotFound, "Can't guess decorator for #{object_or_enumerable.class.name} object")
87
+ end
88
+
89
+ def decorable_object?(object_or_collection)
90
+ (object_or_collection.respond_to?(:empty?) && object_or_collection.empty?) \
91
+ || !object_or_collection \
92
+ || object_or_collection.is_a?(Dekorator::Base) \
93
+ || (defined?(ActiveRecord::Relation) && object_or_collection.is_a?(Dekorator::DecoratedEnumerableProxy))
94
+ end
95
+
96
+ def _safe_constantize(class_name)
97
+ Object.const_get(class_name)
98
+ rescue NameError => _e
99
+ nil
100
+ end
101
+ end
102
+
103
+ # :nodoc
104
+ def initialize(object)
105
+ @decorated_associations = {}
106
+
107
+ super(object)
108
+ end
109
+
110
+ # :nodoc
111
+ def decorate(object_or_collection, with: :__guess__)
112
+ self.class.decorate(object_or_collection, with: with)
113
+ end
114
+
115
+ # Returns the decorated object.
116
+ #
117
+ # @return [Object] the decorated object.
118
+ def object
119
+ __getobj__
120
+ end
121
+ end
122
+
123
+ if defined?(ActiveRecord::Relation)
124
+ # DecoratedEnumerableProxy is strongly inspired from
125
+ # https://github.com/kiote/activeadmin-poro-decorator/blob/master/lib/activeadmin-poro-decorator.rb#L65
126
+ class DecoratedEnumerableProxy < DelegateClass(ActiveRecord::Relation)
127
+ include Enumerable
128
+
129
+ delegate :as_json, :collect, :map, :each, :[], :all?, :include?,
130
+ :first, :last, :shift, to: :decorated_collection
131
+ delegate :each, to: :to_ary
132
+
133
+ def initialize(decorator_class, collection)
134
+ super(collection)
135
+
136
+ @decorator_class = decorator_class
137
+ end
138
+
139
+ def wrapped_collection
140
+ __getobj__
141
+ end
142
+
143
+ def decorated_collection
144
+ @decorated_collection ||= wrapped_collection.collect { |member| @decorator_class.new(member) }
145
+ end
146
+ alias to_ary decorated_collection
147
+ end
148
+ end
149
+ end
150
+
151
+ require "dekorator/railtie" if defined?(Rails)
@@ -0,0 +1,17 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "active_support/concern"
4
+
5
+ module Dekorator
6
+ module Controller
7
+ extend ActiveSupport::Concern
8
+
9
+ included do
10
+ helper_method :decorate
11
+ end
12
+
13
+ def decorate(object_or_collection, with: nil)
14
+ Dekorator::Base.decorate(object_or_collection, with: with)
15
+ end
16
+ end
17
+ end
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Dekorator
4
+ require "dekorator/rails/controller"
5
+
6
+ class Railtie < ::Rails::Railtie
7
+ config.to_prepare do |_app|
8
+ ActionController::Base.include Dekorator::Controller
9
+ end
10
+
11
+ config.after_initialize do |app|
12
+ app.config.paths.add "app/decorators", eager_load: true
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Dekorator
4
+ VERSION = "1.0.0".freeze
5
+ end
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "rails/generators"
4
+
5
+ class DecoratorGenerator < ::Rails::Generators::NamedBase
6
+ invoke "dekorator:decorator"
7
+ end
@@ -0,0 +1,9 @@
1
+ Description:
2
+ Generate a fresh new decorator
3
+
4
+ Example:
5
+ `rails generate dekorator:decorator User`
6
+
7
+ User decorator.
8
+ Decorator: app/decorators/user_decorator.rb
9
+ Test: test/decorators/user_decorator_test.rb
@@ -0,0 +1,17 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "rails/generators"
4
+
5
+ module Dekorator
6
+ module Generators
7
+ class DecoratorGenerator < ::Rails::Generators::NamedBase
8
+ source_root File.expand_path("templates", __dir__)
9
+
10
+ def create_decorator
11
+ template "decorator.rb", File.join("app/decorators", class_path, "#{file_name}_decorator.rb")
12
+ end
13
+
14
+ hook_for :test_framework
15
+ end
16
+ end
17
+ end
@@ -0,0 +1,17 @@
1
+ # frozen_string_literal: true
2
+
3
+ <% module_namespacing do -%>
4
+ class <%= class_name %>Decorator < ApplicationDecorator
5
+ # include ActionView::Helpers::TextHelper
6
+ #
7
+ # decorates_association :posts
8
+ #
9
+ # def full_name
10
+ # [first_name, last_name].join(" ")
11
+ # end
12
+ #
13
+ # def biography_summary
14
+ # truncate(biography, length: 170)
15
+ # end
16
+ end
17
+ <% end -%>
@@ -0,0 +1,37 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "rails/generators"
4
+
5
+ module Dekorator
6
+ module Generators
7
+ class InstallGenerator < ::Rails::Generators::Base
8
+
9
+ def create_root_directory
10
+ empty_directory(dekorator_root_directory)
11
+
12
+ concerns_directory = dekorator_root_directory.join("concerns")
13
+ empty_directory(concerns_directory)
14
+ create_file("#{concerns_directory}/.keep")
15
+ end
16
+
17
+ def create_application_decorator
18
+ create_file application_decorator_path, <<-RUBY
19
+ # frozen_string_literal: true
20
+
21
+ class ApplicationDecorator < Dekorator::Base
22
+ end
23
+ RUBY
24
+ end
25
+
26
+ protected
27
+
28
+ def dekorator_root_directory
29
+ Rails.root.join("app/decorators")
30
+ end
31
+
32
+ def application_decorator_path
33
+ dekorator_root_directory.join("application_decorator.rb")
34
+ end
35
+ end
36
+ end
37
+ end
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "rails/generators"
4
+
5
+ module Rspec
6
+ module Generators
7
+ class DecoratorGenerator < ::Rails::Generators::NamedBase
8
+ source_root File.expand_path("templates", __dir__)
9
+
10
+ def create_decorator_spec
11
+ template "decorator_spec.rb", File.join("spec/decorators", class_path, "#{file_name}_decorator_spec.rb")
12
+ end
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,17 @@
1
+ # frozen_string_literal: true
2
+
3
+ require '<%= File.exists?("spec/rails_helper.rb") ? "rails_helper" : "spec_helper" %>'
4
+
5
+ # Example:
6
+ #
7
+ # describe <%= class_name %>Decorator, type: :decorator do
8
+ # let(:object) { User.new(first_name: "John", last_name: "Doe") }
9
+ # let(:decorated_user) { described_class.new(object) }
10
+ #
11
+ # describe "#full_name" do
12
+ # it { expect(decorated_user.full_name).to eq("John Doe") }
13
+ # end
14
+ # end
15
+ RSpec.describe <%= class_name %>Decorator, type: :decorator do
16
+ pending "add some examples to (or delete) #{__FILE__}"
17
+ end
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "rails/generators"
4
+
5
+ module TestUnit
6
+ module Generators
7
+ class DecoratorGenerator < ::Rails::Generators::NamedBase
8
+ source_root File.expand_path("templates", __dir__)
9
+
10
+ def create_decorator_test
11
+ template "decorator_test.rb", File.join("test/decorators", class_path, "#{file_name}_decorator_test.rb")
12
+ end
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,6 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'test_helper'
4
+
5
+ class <%= class_name %>DecoratorTest < ActiveSupport::TestCase
6
+ end
metadata ADDED
@@ -0,0 +1,173 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: dekorator
3
+ version: !ruby/object:Gem::Version
4
+ version: 1.0.0
5
+ platform: ruby
6
+ authors:
7
+ - Pantographe
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2019-12-02 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: actionview
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '5.0'
20
+ - - "<"
21
+ - !ruby/object:Gem::Version
22
+ version: '6.1'
23
+ type: :runtime
24
+ prerelease: false
25
+ version_requirements: !ruby/object:Gem::Requirement
26
+ requirements:
27
+ - - ">="
28
+ - !ruby/object:Gem::Version
29
+ version: '5.0'
30
+ - - "<"
31
+ - !ruby/object:Gem::Version
32
+ version: '6.1'
33
+ - !ruby/object:Gem::Dependency
34
+ name: activesupport
35
+ requirement: !ruby/object:Gem::Requirement
36
+ requirements:
37
+ - - ">="
38
+ - !ruby/object:Gem::Version
39
+ version: '5.0'
40
+ - - "<"
41
+ - !ruby/object:Gem::Version
42
+ version: '6.1'
43
+ type: :runtime
44
+ prerelease: false
45
+ version_requirements: !ruby/object:Gem::Requirement
46
+ requirements:
47
+ - - ">="
48
+ - !ruby/object:Gem::Version
49
+ version: '5.0'
50
+ - - "<"
51
+ - !ruby/object:Gem::Version
52
+ version: '6.1'
53
+ - !ruby/object:Gem::Dependency
54
+ name: railties
55
+ requirement: !ruby/object:Gem::Requirement
56
+ requirements:
57
+ - - ">="
58
+ - !ruby/object:Gem::Version
59
+ version: '5.0'
60
+ - - "<"
61
+ - !ruby/object:Gem::Version
62
+ version: '6.1'
63
+ type: :runtime
64
+ prerelease: false
65
+ version_requirements: !ruby/object:Gem::Requirement
66
+ requirements:
67
+ - - ">="
68
+ - !ruby/object:Gem::Version
69
+ version: '5.0'
70
+ - - "<"
71
+ - !ruby/object:Gem::Version
72
+ version: '6.1'
73
+ - !ruby/object:Gem::Dependency
74
+ name: bundler
75
+ requirement: !ruby/object:Gem::Requirement
76
+ requirements:
77
+ - - "~>"
78
+ - !ruby/object:Gem::Version
79
+ version: '2.0'
80
+ type: :development
81
+ prerelease: false
82
+ version_requirements: !ruby/object:Gem::Requirement
83
+ requirements:
84
+ - - "~>"
85
+ - !ruby/object:Gem::Version
86
+ version: '2.0'
87
+ - !ruby/object:Gem::Dependency
88
+ name: rake
89
+ requirement: !ruby/object:Gem::Requirement
90
+ requirements:
91
+ - - "~>"
92
+ - !ruby/object:Gem::Version
93
+ version: '10.0'
94
+ type: :development
95
+ prerelease: false
96
+ version_requirements: !ruby/object:Gem::Requirement
97
+ requirements:
98
+ - - "~>"
99
+ - !ruby/object:Gem::Version
100
+ version: '10.0'
101
+ - !ruby/object:Gem::Dependency
102
+ name: rspec
103
+ requirement: !ruby/object:Gem::Requirement
104
+ requirements:
105
+ - - "~>"
106
+ - !ruby/object:Gem::Version
107
+ version: '3.0'
108
+ type: :development
109
+ prerelease: false
110
+ version_requirements: !ruby/object:Gem::Requirement
111
+ requirements:
112
+ - - "~>"
113
+ - !ruby/object:Gem::Version
114
+ version: '3.0'
115
+ description: An opinionated way of organizing model-view code in Ruby on Rails, based
116
+ on decorators
117
+ email:
118
+ - oss@pantographe.studio
119
+ executables: []
120
+ extensions: []
121
+ extra_rdoc_files: []
122
+ files:
123
+ - ".github/workflows/test.yml"
124
+ - CHANGELOG.md
125
+ - CODE_OF_CONDUCT.md
126
+ - LICENSE.txt
127
+ - README.md
128
+ - Rakefile
129
+ - benchmarks/README.md
130
+ - benchmarks/benchmark.rb
131
+ - dekorator.gemspec
132
+ - lib/dekorator.rb
133
+ - lib/dekorator/rails/controller.rb
134
+ - lib/dekorator/railtie.rb
135
+ - lib/dekorator/version.rb
136
+ - lib/generators/decorator_generator.rb
137
+ - lib/generators/dekorator/decorator/USAGE
138
+ - lib/generators/dekorator/decorator/decorator_generator.rb
139
+ - lib/generators/dekorator/decorator/templates/decorator.rb
140
+ - lib/generators/dekorator/install/install_generator.rb
141
+ - lib/generators/rspec/decorator_generator.rb
142
+ - lib/generators/rspec/templates/decorator_spec.rb
143
+ - lib/generators/test_unit/decorator_generator.rb
144
+ - lib/generators/test_unit/templates/decorator_test.rb
145
+ homepage: http://komponent.io
146
+ licenses:
147
+ - MIT
148
+ metadata:
149
+ homepage_uri: https://github.com/komposable/dekorator
150
+ changelog_uri: https://github.com/komposable/dekorator/blob/master/CHANGELOG.md
151
+ source_code_uri: https://github.com/komposable/dekorator
152
+ bug_tracker_uri: https://github.com/komposable/dekorator/issues
153
+ post_install_message:
154
+ rdoc_options: []
155
+ require_paths:
156
+ - lib
157
+ required_ruby_version: !ruby/object:Gem::Requirement
158
+ requirements:
159
+ - - ">="
160
+ - !ruby/object:Gem::Version
161
+ version: '2.3'
162
+ required_rubygems_version: !ruby/object:Gem::Requirement
163
+ requirements:
164
+ - - ">="
165
+ - !ruby/object:Gem::Version
166
+ version: '0'
167
+ requirements: []
168
+ rubygems_version: 3.0.6
169
+ signing_key:
170
+ specification_version: 4
171
+ summary: An opinionated way of organizing model-view code in Ruby on Rails, based
172
+ on decorators
173
+ test_files: []