I needed a way to find delegated methods in GitLab codebase for testing, so I came up with this.
delegated = delegates(project, :ci_cd_settings)
def delegates(fromobj, tosym)
# Get map of delegated methods.
# Rails doesn't maintain a table of delegated methods, so it needs to be
# reconstructed by parsing methods source.
regex = /^\s*delegate .*to: \s*:#{tosym}.*/mx
delegated = {}
fromobj.methods.each do |symname|
method = fromobj.method(symname)
next unless method.source_location
next unless method.source =~ regex
name = symname.to_s
# Example for `Project.last.method("ci_opt_in_jwt").source``
# " delegate :opt_in_jwt, :opt_in_jwt=, to: :ci_cd_settings, prefix: :ci, allow_nil: true\n"
prefix_match = method.source.match /prefix: \s+ :(\w+)/mx
delegated[name] =
if prefix_match
name.delete_prefix("#{prefix_match[1]}_")
else
name
end
end
delegated
end
Top comments (0)