Inspecting Ruby Method Params

At work, a colleague of mine created a gem that our company’s codebase uses. It inspects the Ruby background job classes we have and presents them in a dashboard on the web that allows us to schedule the jobs 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>

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] = params.map(&:last)
=> {:req=>[:a1, :a2], :keyreq=>[:b1], :key=>[:b2]}

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.

Up next Deconstructing Block Arguments In Ruby We usually use block arguments like so: We also know that we can deconstruct the arguments using the splat operator, like so: But what I recently
Latest posts Decorating Service Objects - FunctionalObject Deconstructing Block Arguments In Ruby Inspecting Ruby Method Params