Method Name As Documentation

Burdette Lamar - Jan 22 '18 - - Dev Community

Hey, Ruby coders!

Do you recognize this idiom?

Object.const_get(class_name)
Enter fullscreen mode Exit fullscreen mode

Or this one?

Object.const_get(class_name).new(*args)
Enter fullscreen mode Exit fullscreen mode

When I wanted to do these two things in my RubyTest project, I had to Google to find out how.

Now if I put this code into my project, will I recognize these idioms later on? Next month? Next year?

I could add comments to explain, but a comment can get stale (not keep up with code changes), or get separated from its code, or even get deleted.

You can help your downstream code enhancer/maintainer by pushing an unusual idiom into a well-named method.

(Hint: If you're not sure who is the downstream enhancer/maintainer, it's you!)

Thus, I created this:

class ObjectHelper

  def self.get_class_for_class_name(class_name)
    Object::const_get(class_name)
  end

  def self.instantiate_class_for_class_name(class_name, *args)
    self.get_class_for_class_name(class_name).new(*args)
  end

end
Enter fullscreen mode Exit fullscreen mode

PS: My GitHub project is about test automation in Ruby. It has a Tester Tour of the demo testing for a web UI and for a REST API.

Cross-posted from my blog.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .