Created
May 11, 2022 05:05
-
-
Save leastbad/fc18f2d210afad60ea831b85104a24b7 to your computer and use it in GitHub Desktop.
Alias for_ delegated types in Rails 6.1
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# intended to be a Rails 6.1 initializer based on @rolandstuder's https://github.com/rails/rails/pull/41506 | |
# if you want to use it with Rails 7, you will need to add a third options: parameter to the method | |
module ActiveRecord | |
module DelegatedType | |
private | |
def define_delegated_type_methods(role, types:) | |
role_type = "#{role}_type" | |
role_id = "#{role}_id" | |
define_method "#{role}_class" do | |
public_send("#{role}_type").constantize | |
end | |
define_method "#{role}_name" do | |
public_send("#{role}_class").model_name.singular.inquiry | |
end | |
types.each do |type| | |
scope_name = type.tableize.gsub("/", "_") | |
aliased_scope_name = "for_#{scope_name}" | |
singular = scope_name.singularize | |
query = "#{singular}?" | |
scope scope_name, -> { where(role_type => type) } | |
define_singleton_method(aliased_scope_name, singleton_method(scope_name)) | |
define_method query do | |
public_send(role_type) == type | |
end | |
define_method singular do | |
public_send(role) if public_send(query) | |
end | |
define_method "#{singular}_id" do | |
public_send(role_id) if public_send(query) | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment