DEV Community

Daniel Goh
Daniel Goh

Posted on

Inspecting Ruby Method Params

At work, my colleague created a gem that is used by the company's codebase. It's an extension to Sidekiq- it inspects the Ruby background job classes we have and adds a page on Sidekiq's dashboard. This allows us to schedule whatever jobs we have "adhoc".

Therefore, it needs to know what arguments each job accepts, and accept parameters that are input via the web and feed them properly when calling the job classes.

In Ruby, this means, it needs to be able to discern between positional arguments and keyword arguments. I dug through the gem a little to open a PR to modify it, and just wanted to share how Ruby allows you to introspect methods.

In ruby, a class method can stand on it's own as an object like so

class Foo
  def bar(a1, a2, b1:, b2: true);end

meth = Foo.instance_method(:bar)
=> #<UnboundMethod: Foo#bar(a1, a2, b1:, b2: ...) (irb):12>
Enter fullscreen mode Exit fullscreen mode

The method object has a few cool instance methods you can call. One of them is #parameters. It will spit out the types of methods it receives in detail.

=> [[:req, :a1], [:req, :a2], [:keyreq, :b1], [:key, :b2]]

  .group_by { |type, _| type }
  .each_with_object({}) do |(type, params), acc|
    acc[type] =
=> {:req=>[:a1, :a2], :keyreq=>[:b1], :key=>[:b2]}
Enter fullscreen mode Exit fullscreen mode

Here's the official docs that contains a full list of other instance methods that can be called on the Method object.

And here is the PR that I opened in my colleague's gem, for reference.

Top comments (0)