delegated_type 0.1.0
Sign up to get free protection for your applications and to get access to all the features.
- checksums.yaml +7 -0
- data/.gitignore +8 -0
- data/CODE_OF_CONDUCT.md +74 -0
- data/Gemfile +7 -0
- data/LICENSE.txt +21 -0
- data/README.md +142 -0
- data/Rakefile +10 -0
- data/bin/console +14 -0
- data/bin/setup +8 -0
- data/delegated_type.gemspec +33 -0
- data/lib/delegated_type.rb +213 -0
- data/lib/delegated_type/version.rb +3 -0
- metadata +94 -0
checksums.yaml
ADDED
@@ -0,0 +1,7 @@
|
|
1
|
+
---
|
2
|
+
SHA256:
|
3
|
+
metadata.gz: e1446c9c7d665335324fb57dab6bde3e42c492f4ed8f11500ad224128f60bbdc
|
4
|
+
data.tar.gz: 5cb68e6be82b82c8fffb1b01c8fe8ed21e5fd6cce446dd5f4dc9c407c71528b3
|
5
|
+
SHA512:
|
6
|
+
metadata.gz: edf629e662e3f952dbe1fa748df6091cffdae9c501940ef024f42171a903ad990d50e76efc2ad0ae81d0fd6f89234723c88f581526f89dc4a752e5c3b466a952
|
7
|
+
data.tar.gz: 3173d0f375615c5a10a6f70ee6d9de60280cb93ee0ccd0bfcdb21d5a109bf22fadf5291d0c0ad9f69a26d70bad845f6181fd2aca345c97e62c7949847280ee4f
|
data/.gitignore
ADDED
data/CODE_OF_CONDUCT.md
ADDED
@@ -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 rjmaltamar@gmail.com. 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 [https://contributor-covenant.org/version/1/4][version]
|
72
|
+
|
73
|
+
[homepage]: https://contributor-covenant.org
|
74
|
+
[version]: https://contributor-covenant.org/version/1/4/
|
data/Gemfile
ADDED
data/LICENSE.txt
ADDED
@@ -0,0 +1,21 @@
|
|
1
|
+
The MIT License (MIT)
|
2
|
+
|
3
|
+
Copyright (c) 2020 TODO: Write your name
|
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,142 @@
|
|
1
|
+
# Delegated types
|
2
|
+
|
3
|
+
Class hierarchies can map to relational database tables in many ways. Active Record, for example, offers purely abstract classes, where the superclass doesn't persist any attributes, and single-table inheritance, where all attributes from all levels of the hierarchy are represented in a single table. Both have their places, but neither are without their drawbacks.
|
4
|
+
|
5
|
+
The problem with purely abstract classes is that all concrete subclasses must persist all the shared attributes themselves in their own tables (also known as class-table inheritance). This makes it hard to do queries across the hierarchy. For example, imagine you have the following hierarchy:
|
6
|
+
|
7
|
+
|
8
|
+
```ruby
|
9
|
+
Entry < ApplicationRecord
|
10
|
+
Message < Entry
|
11
|
+
Comment < Entry
|
12
|
+
```
|
13
|
+
|
14
|
+
How do you show a feed that has both +Message+ and +Comment+ records, which can be easily paginated? Well, you can't! Messages are backed by a messages table and comments by a comments table. You can't pull from both tables at once and use a consistent OFFSET/LIMIT scheme.
|
15
|
+
|
16
|
+
You can get around the pagination problem by using single-table inheritance, but now you're forced into a single mega table with all the attributes from all subclasses. No matter how divergent. If a Messagehas a subject, but the comment does not, well, now the comment does anyway! So STI works best when there's little divergence between the subclasses and their attributes.
|
17
|
+
|
18
|
+
But there's a third way: Delegated types. With this approach, the "superclass" is a concrete class that is represented by its own table, where all the superclass attributes that are shared amongst all the "subclasses" are stored. And then each of the subclasses have their own individual tables for additional attributes that are particular to their implementation. This is similar to what's called multi-table inheritance in Django, but instead of actual inheritance, this approach uses delegation to form the hierarchy and share responsibilities.
|
19
|
+
|
20
|
+
|
21
|
+
Let's look at that entry/message/comment example using delegated types:
|
22
|
+
|
23
|
+
```ruby
|
24
|
+
# Schema: entries[ id, account_id, creator_id, created_at, updated_at, entryable_type, entryable_id ]
|
25
|
+
class Entry < ApplicationRecord
|
26
|
+
belongs_to :account
|
27
|
+
belongs_to :creator
|
28
|
+
delegated_type :entryable, types: %w[ Message Comment ]
|
29
|
+
end
|
30
|
+
|
31
|
+
module Entryable
|
32
|
+
extend ActiveSupport::Concern
|
33
|
+
|
34
|
+
included do
|
35
|
+
has_one :entry, as: :entryable, touch: true
|
36
|
+
end
|
37
|
+
end
|
38
|
+
|
39
|
+
# Schema: messages[ id, subject ]
|
40
|
+
class Message < ApplicationRecord
|
41
|
+
include Entryable
|
42
|
+
has_rich_text :content
|
43
|
+
end
|
44
|
+
|
45
|
+
# Schema: comments[ id, content ]
|
46
|
+
class Comment < ApplicationRecord
|
47
|
+
include Entryable
|
48
|
+
end
|
49
|
+
```
|
50
|
+
|
51
|
+
As you can see, neither +Message+ nor +Comment+ are meant to stand alone. Crucial metadata for both classes resides in the +Entry+ "superclass". But the +Entry+ absolutely can stand alone in terms of querying capacity in particular. You can now easily do things like:
|
52
|
+
|
53
|
+
```ruby
|
54
|
+
Account.entries.order(created_at: :desc).limit(50)
|
55
|
+
```
|
56
|
+
|
57
|
+
Which is exactly what you want when displaying both comments and messages together. The entry itself can be rendered as its delegated type easily, like so:
|
58
|
+
|
59
|
+
```erb
|
60
|
+
# entries/_entry.html.erb
|
61
|
+
<%= render "entries/entryables/#{entry.entryable_name}", entry: entry %>
|
62
|
+
|
63
|
+
# entries/entryables/_message.html.erb
|
64
|
+
<div class="message">
|
65
|
+
Posted on <%= entry.created_at %> by <%= entry.creator.name %>: <%= entry.message.content %>
|
66
|
+
</div>
|
67
|
+
|
68
|
+
# entries/entryables/_comment.html.erb
|
69
|
+
<div class="comment">
|
70
|
+
<%= entry.creator.name %> said: <%= entry.comment.content %>
|
71
|
+
</div>
|
72
|
+
```
|
73
|
+
|
74
|
+
## Sharing behavior with concerns and controllers
|
75
|
+
|
76
|
+
The entry "superclass" also serves as a perfect place to put all that shared logic that applies to both messages and comments, and which acts primarily on the shared attributes. Imagine:
|
77
|
+
|
78
|
+
```ruby
|
79
|
+
class Entry < ApplicationRecord
|
80
|
+
include Eventable, Forwardable, Redeliverable
|
81
|
+
end
|
82
|
+
```
|
83
|
+
|
84
|
+
Which allows you to have controllers for things like +ForwardsController+ and +RedeliverableController+ that both act on entries, and thus provide the shared functionality to both messages and comments.
|
85
|
+
|
86
|
+
## Creating new records
|
87
|
+
|
88
|
+
You create a new record that uses delegated typing by creating the delegator and delegatee at the same time, like so:
|
89
|
+
|
90
|
+
```ruby
|
91
|
+
Entry.create! entryable: Comment.new(content: "Hello!"), creator: Current.user
|
92
|
+
```
|
93
|
+
|
94
|
+
If you need more complicated composition, or you need to perform dependent validation, you should build a factory method or class to take care of the complicated needs. This could be as simple as:
|
95
|
+
|
96
|
+
```ruby
|
97
|
+
class Entry < ApplicationRecord
|
98
|
+
def self.create_with_comment(content, creator: Current.user)
|
99
|
+
create! entryable: Comment.new(content: content), creator: creator
|
100
|
+
end
|
101
|
+
end
|
102
|
+
```
|
103
|
+
|
104
|
+
## Adding further delegation
|
105
|
+
|
106
|
+
The delegated type shouldn't just answer the question of what the underlying class is called. In fact, that's an anti-pattern most of the time. The reason you're building this hierarchy is to take advantage of polymorphism. So here's a simple example of that:
|
107
|
+
|
108
|
+
```ruby
|
109
|
+
class Entry < ApplicationRecord
|
110
|
+
delegated_type :entryable, types: %w[ Message Comment ]
|
111
|
+
delegate :title, to: :entryable
|
112
|
+
end
|
113
|
+
|
114
|
+
class Message < ApplicationRecord
|
115
|
+
def title
|
116
|
+
subject
|
117
|
+
end
|
118
|
+
end
|
119
|
+
|
120
|
+
class Comment < ApplicationRecord
|
121
|
+
def title
|
122
|
+
content.truncate(20)
|
123
|
+
end
|
124
|
+
end
|
125
|
+
```
|
126
|
+
|
127
|
+
Now you can list a bunch of entries, call `Entry#title`, and polymorphism will provide you with the answer.
|
128
|
+
|
129
|
+
|
130
|
+
|
131
|
+
## Contributing
|
132
|
+
|
133
|
+
Bug reports and pull requests are welcome on GitHub at https://github.com/robertomiranda/delegated_type. 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/[USERNAME]/delegated_type/blob/master/CODE_OF_CONDUCT.md).
|
134
|
+
|
135
|
+
|
136
|
+
## License
|
137
|
+
|
138
|
+
The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
|
139
|
+
|
140
|
+
## Code of Conduct
|
141
|
+
|
142
|
+
Everyone interacting in the DelegatedType project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/delegated_type/blob/master/CODE_OF_CONDUCT.md).
|
data/Rakefile
ADDED
data/bin/console
ADDED
@@ -0,0 +1,14 @@
|
|
1
|
+
#!/usr/bin/env ruby
|
2
|
+
|
3
|
+
require "bundler/setup"
|
4
|
+
require "delegated_type"
|
5
|
+
|
6
|
+
# You can add fixtures and/or initialization code here to make experimenting
|
7
|
+
# with your gem easier. You can also use a different console, if you like.
|
8
|
+
|
9
|
+
# (If you use this, don't forget to add pry to your Gemfile!)
|
10
|
+
# require "pry"
|
11
|
+
# Pry.start
|
12
|
+
|
13
|
+
require "irb"
|
14
|
+
IRB.start(__FILE__)
|
data/bin/setup
ADDED
@@ -0,0 +1,33 @@
|
|
1
|
+
require_relative 'lib/delegated_type/version'
|
2
|
+
|
3
|
+
Gem::Specification.new do |spec|
|
4
|
+
spec.name = "delegated_type"
|
5
|
+
spec.version = DelegatedType::VERSION
|
6
|
+
spec.authors = ["Roberto Miranda Altamar"]
|
7
|
+
spec.email = ["rjmaltamar@gmail.com"]
|
8
|
+
|
9
|
+
spec.summary = %q{delegated_type is an alternative to single-table inheritance for representing class hierarchies. Backport of ActiveRecord::DelegatedType 6.1 to AR 5.x and 6.x}
|
10
|
+
spec.description = %q{The second type of model inheritance supported from rails 6.1, delegated type, where each sub-model has its own database table and can be queried and created individually.}
|
11
|
+
spec.homepage = "https://github.com/robertomiranda/delegated_type"
|
12
|
+
spec.license = "MIT"
|
13
|
+
spec.required_ruby_version = Gem::Requirement.new(">= 2.3.0")
|
14
|
+
|
15
|
+
spec.metadata["allowed_push_host"] = "https://rubygems.org/"
|
16
|
+
|
17
|
+
spec.metadata["homepage_uri"] = spec.homepage
|
18
|
+
spec.metadata["source_code_uri"] = spec.homepage
|
19
|
+
# spec.metadata["changelog_uri"] = "TODO: Put your gem's CHANGELOG.md URL here."
|
20
|
+
|
21
|
+
# Specify which files should be added to the gem when it is released.
|
22
|
+
# The `git ls-files -z` loads the files in the RubyGem that have been added into git.
|
23
|
+
spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do
|
24
|
+
`git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
|
25
|
+
end
|
26
|
+
spec.bindir = "exe"
|
27
|
+
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
|
28
|
+
spec.require_paths = ["lib"]
|
29
|
+
|
30
|
+
spec.add_dependency "activerecord", [">= 5.0", "< 6.1"]
|
31
|
+
|
32
|
+
spec.add_development_dependency 'sqlite3'
|
33
|
+
end
|
@@ -0,0 +1,213 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
require "delegated_type/version"
|
3
|
+
require "active_record"
|
4
|
+
require "active_support/core_ext/string/inquiry"
|
5
|
+
|
6
|
+
module ActiveRecord
|
7
|
+
# == Delegated types
|
8
|
+
#
|
9
|
+
# Class hierarchies can map to relational database tables in many ways. Active Record, for example, offers
|
10
|
+
# purely abstract classes, where the superclass doesn't persist any attributes, and single-table inheritance,
|
11
|
+
# where all attributes from all levels of the hierarchy are represented in a single table. Both have their
|
12
|
+
# places, but neither are without their drawbacks.
|
13
|
+
#
|
14
|
+
# The problem with purely abstract classes is that all concrete subclasses must persist all the shared
|
15
|
+
# attributes themselves in their own tables (also known as class-table inheritance). This makes it hard to
|
16
|
+
# do queries across the hierarchy. For example, imagine you have the following hierarchy:
|
17
|
+
#
|
18
|
+
# Entry < ApplicationRecord
|
19
|
+
# Message < Entry
|
20
|
+
# Comment < Entry
|
21
|
+
#
|
22
|
+
# How do you show a feed that has both +Message+ and +Comment+ records, which can be easily paginated?
|
23
|
+
# Well, you can't! Messages are backed by a messages table and comments by a comments table. You can't
|
24
|
+
# pull from both tables at once and use a consistent OFFSET/LIMIT scheme.
|
25
|
+
#
|
26
|
+
# You can get around the pagination problem by using single-table inheritance, but now you're forced into
|
27
|
+
# a single mega table with all the attributes from all subclasses. No matter how divergent. If a Message
|
28
|
+
# has a subject, but the comment does not, well, now the comment does anyway! So STI works best when there's
|
29
|
+
# little divergence between the subclasses and their attributes.
|
30
|
+
#
|
31
|
+
# But there's a third way: Delegated types. With this approach, the "superclass" is a concrete class
|
32
|
+
# that is represented by its own table, where all the superclass attributes that are shared amongst all the
|
33
|
+
# "subclasses" are stored. And then each of the subclasses have their own individual tables for additional
|
34
|
+
# attributes that are particular to their implementation. This is similar to what's called multi-table
|
35
|
+
# inheritance in Django, but instead of actual inheritance, this approach uses delegation to form the
|
36
|
+
# hierarchy and share responsibilities.
|
37
|
+
#
|
38
|
+
# Let's look at that entry/message/comment example using delegated types:
|
39
|
+
#
|
40
|
+
# # Schema: entries[ id, account_id, creator_id, created_at, updated_at, entryable_type, entryable_id ]
|
41
|
+
# class Entry < ApplicationRecord
|
42
|
+
# belongs_to :account
|
43
|
+
# belongs_to :creator
|
44
|
+
# delegated_type :entryable, types: %w[ Message Comment ]
|
45
|
+
# end
|
46
|
+
#
|
47
|
+
# module Entryable
|
48
|
+
# extend ActiveSupport::Concern
|
49
|
+
#
|
50
|
+
# included do
|
51
|
+
# has_one :entry, as: :entryable, touch: true
|
52
|
+
# end
|
53
|
+
# end
|
54
|
+
#
|
55
|
+
# # Schema: messages[ id, subject ]
|
56
|
+
# class Message < ApplicationRecord
|
57
|
+
# include Entryable
|
58
|
+
# has_rich_text :content
|
59
|
+
# end
|
60
|
+
#
|
61
|
+
# # Schema: comments[ id, content ]
|
62
|
+
# class Comment < ApplicationRecord
|
63
|
+
# include Entryable
|
64
|
+
# end
|
65
|
+
#
|
66
|
+
# As you can see, neither +Message+ nor +Comment+ are meant to stand alone. Crucial metadata for both classes
|
67
|
+
# resides in the +Entry+ "superclass". But the +Entry+ absolutely can stand alone in terms of querying capacity
|
68
|
+
# in particular. You can now easily do things like:
|
69
|
+
#
|
70
|
+
# Account.entries.order(created_at: :desc).limit(50)
|
71
|
+
#
|
72
|
+
# Which is exactly what you want when displaying both comments and messages together. The entry itself can
|
73
|
+
# be rendered as its delegated type easily, like so:
|
74
|
+
#
|
75
|
+
# # entries/_entry.html.erb
|
76
|
+
# <%= render "entries/entryables/#{entry.entryable_name}", entry: entry %>
|
77
|
+
#
|
78
|
+
# # entries/entryables/_message.html.erb
|
79
|
+
# <div class="message">
|
80
|
+
# Posted on <%= entry.created_at %> by <%= entry.creator.name %>: <%= entry.message.content %>
|
81
|
+
# </div>
|
82
|
+
#
|
83
|
+
# # entries/entryables/_comment.html.erb
|
84
|
+
# <div class="comment">
|
85
|
+
# <%= entry.creator.name %> said: <%= entry.comment.content %>
|
86
|
+
# </div>
|
87
|
+
#
|
88
|
+
# == Sharing behavior with concerns and controllers
|
89
|
+
#
|
90
|
+
# The entry "superclass" also serves as a perfect place to put all that shared logic that applies to both
|
91
|
+
# messages and comments, and which acts primarily on the shared attributes. Imagine:
|
92
|
+
#
|
93
|
+
# class Entry < ApplicationRecord
|
94
|
+
# include Eventable, Forwardable, Redeliverable
|
95
|
+
# end
|
96
|
+
#
|
97
|
+
# Which allows you to have controllers for things like +ForwardsController+ and +RedeliverableController+
|
98
|
+
# that both act on entries, and thus provide the shared functionality to both messages and comments.
|
99
|
+
#
|
100
|
+
# == Creating new records
|
101
|
+
#
|
102
|
+
# You create a new record that uses delegated typing by creating the delegator and delegatee at the same time,
|
103
|
+
# like so:
|
104
|
+
#
|
105
|
+
# Entry.create! entryable: Comment.new(content: "Hello!"), creator: Current.user
|
106
|
+
#
|
107
|
+
# If you need more complicated composition, or you need to perform dependent validation, you should build a factory
|
108
|
+
# method or class to take care of the complicated needs. This could be as simple as:
|
109
|
+
#
|
110
|
+
# class Entry < ApplicationRecord
|
111
|
+
# def self.create_with_comment(content, creator: Current.user)
|
112
|
+
# create! entryable: Comment.new(content: content), creator: creator
|
113
|
+
# end
|
114
|
+
# end
|
115
|
+
#
|
116
|
+
# == Adding further delegation
|
117
|
+
#
|
118
|
+
# The delegated type shouldn't just answer the question of what the underlying class is called. In fact, that's
|
119
|
+
# an anti-pattern most of the time. The reason you're building this hierarchy is to take advantage of polymorphism.
|
120
|
+
# So here's a simple example of that:
|
121
|
+
#
|
122
|
+
# class Entry < ApplicationRecord
|
123
|
+
# delegated_type :entryable, types: %w[ Message Comment ]
|
124
|
+
# delegate :title, to: :entryable
|
125
|
+
# end
|
126
|
+
#
|
127
|
+
# class Message < ApplicationRecord
|
128
|
+
# def title
|
129
|
+
# subject
|
130
|
+
# end
|
131
|
+
# end
|
132
|
+
#
|
133
|
+
# class Comment < ApplicationRecord
|
134
|
+
# def title
|
135
|
+
# content.truncate(20)
|
136
|
+
# end
|
137
|
+
# end
|
138
|
+
#
|
139
|
+
# Now you can list a bunch of entries, call +Entry#title+, and polymorphism will provide you with the answer.
|
140
|
+
module DelegatedType
|
141
|
+
# Defines this as a class that'll delegate its type for the passed +role+ to the class references in +types+.
|
142
|
+
# That'll create a polymorphic +belongs_to+ relationship to that +role+, and it'll add all the delegated
|
143
|
+
# type convenience methods:
|
144
|
+
#
|
145
|
+
# class Entry < ApplicationRecord
|
146
|
+
# delegated_type :entryable, types: %w[ Message Comment ], dependent: :destroy
|
147
|
+
# end
|
148
|
+
#
|
149
|
+
# Entry#entryable_class # => +Message+ or +Comment+
|
150
|
+
# Entry#entryable_name # => "message" or "comment"
|
151
|
+
# Entry.messages # => Entry.where(entryable_type: "Message")
|
152
|
+
# Entry#message? # => true when entryable_type == "Message"
|
153
|
+
# Entry#message # => returns the message record, when entryable_type == "Message", otherwise nil
|
154
|
+
# Entry#message_id # => returns entryable_id, when entryable_type == "Message", otherwise nil
|
155
|
+
# Entry.comments # => Entry.where(entryable_type: "Comment")
|
156
|
+
# Entry#comment? # => true when entryable_type == "Comment"
|
157
|
+
# Entry#comment # => returns the comment record, when entryable_type == "Comment", otherwise nil
|
158
|
+
# Entry#comment_id # => returns entryable_id, when entryable_type == "Comment", otherwise nil
|
159
|
+
#
|
160
|
+
# The +options+ are passed directly to the +belongs_to+ call, so this is where you declare +dependent+ etc.
|
161
|
+
#
|
162
|
+
# You can also declare namespaced types:
|
163
|
+
#
|
164
|
+
# class Entry < ApplicationRecord
|
165
|
+
# delegated_type :entryable, types: %w[ Message Comment Access::NoticeMessage ], dependent: :destroy
|
166
|
+
# end
|
167
|
+
#
|
168
|
+
# Entry.access_notice_messages
|
169
|
+
# entry.access_notice_message
|
170
|
+
# entry.access_notice_message?
|
171
|
+
def delegated_type(role, types:, **options)
|
172
|
+
belongs_to role, options.delete(:scope), **options.merge(polymorphic: true)
|
173
|
+
define_delegated_type_methods role, types: types
|
174
|
+
end
|
175
|
+
|
176
|
+
private
|
177
|
+
def define_delegated_type_methods(role, types:)
|
178
|
+
role_type = "#{role}_type"
|
179
|
+
role_id = "#{role}_id"
|
180
|
+
|
181
|
+
define_method "#{role}_class" do
|
182
|
+
public_send("#{role}_type").constantize
|
183
|
+
end
|
184
|
+
|
185
|
+
define_method "#{role}_name" do
|
186
|
+
public_send("#{role}_class").model_name.singular.inquiry
|
187
|
+
end
|
188
|
+
|
189
|
+
types.each do |type|
|
190
|
+
scope_name = type.tableize.gsub("/", "_")
|
191
|
+
singular = scope_name.singularize
|
192
|
+
query = "#{singular}?"
|
193
|
+
|
194
|
+
scope scope_name, -> { where(role_type => type) }
|
195
|
+
|
196
|
+
define_method query do
|
197
|
+
public_send(role_type) == type
|
198
|
+
end
|
199
|
+
|
200
|
+
define_method singular do
|
201
|
+
public_send(role) if public_send(query)
|
202
|
+
end
|
203
|
+
|
204
|
+
define_method "#{singular}_id" do
|
205
|
+
public_send(role_id) if public_send(query)
|
206
|
+
end
|
207
|
+
end
|
208
|
+
end
|
209
|
+
end
|
210
|
+
end
|
211
|
+
|
212
|
+
|
213
|
+
ActiveRecord::Base.send(:extend, ActiveRecord::DelegatedType)
|
metadata
ADDED
@@ -0,0 +1,94 @@
|
|
1
|
+
--- !ruby/object:Gem::Specification
|
2
|
+
name: delegated_type
|
3
|
+
version: !ruby/object:Gem::Version
|
4
|
+
version: 0.1.0
|
5
|
+
platform: ruby
|
6
|
+
authors:
|
7
|
+
- Roberto Miranda Altamar
|
8
|
+
autorequire:
|
9
|
+
bindir: exe
|
10
|
+
cert_chain: []
|
11
|
+
date: 2020-10-17 00:00:00.000000000 Z
|
12
|
+
dependencies:
|
13
|
+
- !ruby/object:Gem::Dependency
|
14
|
+
name: activerecord
|
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: sqlite3
|
35
|
+
requirement: !ruby/object:Gem::Requirement
|
36
|
+
requirements:
|
37
|
+
- - ">="
|
38
|
+
- !ruby/object:Gem::Version
|
39
|
+
version: '0'
|
40
|
+
type: :development
|
41
|
+
prerelease: false
|
42
|
+
version_requirements: !ruby/object:Gem::Requirement
|
43
|
+
requirements:
|
44
|
+
- - ">="
|
45
|
+
- !ruby/object:Gem::Version
|
46
|
+
version: '0'
|
47
|
+
description: The second type of model inheritance supported from rails 6.1, delegated
|
48
|
+
type, where each sub-model has its own database table and can be queried and created
|
49
|
+
individually.
|
50
|
+
email:
|
51
|
+
- rjmaltamar@gmail.com
|
52
|
+
executables: []
|
53
|
+
extensions: []
|
54
|
+
extra_rdoc_files: []
|
55
|
+
files:
|
56
|
+
- ".gitignore"
|
57
|
+
- CODE_OF_CONDUCT.md
|
58
|
+
- Gemfile
|
59
|
+
- LICENSE.txt
|
60
|
+
- README.md
|
61
|
+
- Rakefile
|
62
|
+
- bin/console
|
63
|
+
- bin/setup
|
64
|
+
- delegated_type.gemspec
|
65
|
+
- lib/delegated_type.rb
|
66
|
+
- lib/delegated_type/version.rb
|
67
|
+
homepage: https://github.com/robertomiranda/delegated_type
|
68
|
+
licenses:
|
69
|
+
- MIT
|
70
|
+
metadata:
|
71
|
+
allowed_push_host: https://rubygems.org/
|
72
|
+
homepage_uri: https://github.com/robertomiranda/delegated_type
|
73
|
+
source_code_uri: https://github.com/robertomiranda/delegated_type
|
74
|
+
post_install_message:
|
75
|
+
rdoc_options: []
|
76
|
+
require_paths:
|
77
|
+
- lib
|
78
|
+
required_ruby_version: !ruby/object:Gem::Requirement
|
79
|
+
requirements:
|
80
|
+
- - ">="
|
81
|
+
- !ruby/object:Gem::Version
|
82
|
+
version: 2.3.0
|
83
|
+
required_rubygems_version: !ruby/object:Gem::Requirement
|
84
|
+
requirements:
|
85
|
+
- - ">="
|
86
|
+
- !ruby/object:Gem::Version
|
87
|
+
version: '0'
|
88
|
+
requirements: []
|
89
|
+
rubygems_version: 3.0.3
|
90
|
+
signing_key:
|
91
|
+
specification_version: 4
|
92
|
+
summary: delegated_type is an alternative to single-table inheritance for representing
|
93
|
+
class hierarchies. Backport of ActiveRecord::DelegatedType 6.1 to AR 5.x and 6.x
|
94
|
+
test_files: []
|