DEV Community

Anatoli Babenia
Anatoli Babenia

Posted on

3

Find delegated methods in Ruby on Rails

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)
Enter fullscreen mode Exit fullscreen mode
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
Enter fullscreen mode Exit fullscreen mode

Image of Datadog

How to Diagram Your Cloud Architecture

Cloud architecture diagrams provide critical visibility into the resources in your environment and how they’re connected. In our latest eBook, AWS Solution Architects Jason Mimick and James Wenzel walk through best practices on how to build effective and professional diagrams.

Download the Free eBook

Top comments (0)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More