rubocop / rubocop/ruby-style-guide

Avoiding use of class references built via strings/`constantize`

Open
#806 5 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Approved
Dominant language
No language data
Stars
16.5k
Forks
3.3k
PR merge metrics
No merged PRs in 30d

Description

The problem:

As a developer, if I am changing how a class is used or named, I would need to grep against the codebase with the name of the class. If this class is ever referenced via constantize then I will not find that reference without already knowing it's already there.

eg.

# Class definitions
class AdminUser; end
class RegularUser; end

# bad usage
user_klass = "#{admin_accessible? ? "Admin" : "Regular")}User".constantize

# good usage
user_klass =
  if admin_accessible?
    AdminUser
  else
    RegularUser
  end

The solution:
I think using constantize is the issue here. I think there are cases where it needs to be used, but in general it causes the problem I outlined.

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

The issue names no file, test, or entry point; start with the problem statement and its constantize examples. Review the five-comment discussion to determine the intended scope and exceptions. Done should mean the style guide has an agreed, actionable position on string-built class references.

Written by the indexing model from the issue text.

Assessment

Tech stack
ruby
Domain
documentation
Issue type
Documentation
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
20/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.