Skip to content

Commit 883b033

Browse files
authored
Merge pull request rails#50662 from nubinary/feature/delegated-type-types-introspection
Define a class method to introspect valid delegatable types so they can
2 parents afc7d03 + b3fecab commit 883b033

File tree

4 files changed

+13
-0
lines changed

4 files changed

+13
-0
lines changed

activerecord/CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
* Add `<role>_types` class method to `ActiveRecord::DelegatedType` so that the delegated types can be instrospected
2+
3+
*JP Rosevear*
4+
15
* Make `schema_dump`, `query_cache`, `replica` and `database_tasks` configurable via `DATABASE_URL`
26

37
This wouldn't always work previously because boolean values would be interpreted as strings.

activerecord/lib/active_record/delegated_type.rb

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -219,6 +219,10 @@ def define_delegated_type_methods(role, types:, options:)
219219
role_type = options[:foreign_type] || "#{role}_type"
220220
role_id = options[:foreign_key] || "#{role}_id"
221221

222+
define_singleton_method "#{role}_types" do
223+
types.map(&:to_s)
224+
end
225+
222226
define_method "#{role}_class" do
223227
public_send(role_type).constantize
224228
end

activerecord/test/cases/delegated_type_test.rb

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,10 @@ class DelegatedTypeTest < ActiveRecord::TestCase
2424
end
2525
end
2626

27+
test "delegated types" do
28+
assert_equal ["Message", "Comment"], Entry.entryable_types
29+
end
30+
2731
test "delegated class" do
2832
assert_equal Message, @entry_with_message.entryable_class
2933
assert_equal Comment, @entry_with_comment.entryable_class

guides/source/association_basics.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3007,6 +3007,7 @@ With this definition complete, our `Entry` delegator now provides the following
30073007

30083008
| Method | Return |
30093009
|---|---|
3010+
| `Entry#entryable_types` | ["Message", "Comment"] |
30103011
| `Entry#entryable_class` | Message or Comment |
30113012
| `Entry#entryable_name` | "message" or "comment" |
30123013
| `Entry.messages` | `Entry.where(entryable_type: "Message")` |

0 commit comments

Comments
 (0)