Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Avoiding use of class references built via strings/constantize #806

Open
Skipants opened this issue Feb 28, 2020 · 5 comments
Open

Avoiding use of class references built via strings/constantize #806

Skipants opened this issue Feb 28, 2020 · 5 comments
Labels

Comments

@Skipants
Copy link

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.

@pirj
Copy link
Member

pirj commented Feb 29, 2020

Do you think this is specific to Rails?
I can transfer it to the Ruby Style Guide issue tracker for you.

@Skipants
Copy link
Author

I'm not too sure. constantize is a ActiveSupport method and I think my decision to put it here was based on making a rule around the usage of that method somehow. What's your thoughts on it, @pirj ?

@pirj
Copy link
Member

pirj commented Mar 18, 2020

I mean constantize is definitely a Rails-related method, but is it about constantize or instrumenting class names?

> self.class.const_get("Obj" + "ect")
=> Object

@Skipants
Copy link
Author

Makes sense. Transfer away!

@pirj pirj transferred this issue from rubocop/rails-style-guide Mar 18, 2020
@bbatsov
Copy link
Collaborator

bbatsov commented Mar 28, 2020

PR welcome! :-)

@pirj pirj added the Approved label Feb 23, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants