rubocop / rails-style-guide

A community-driven Ruby on Rails style guide
http://rails.rubystyle.guide
6.47k stars 1.06k forks source link

Cop idea: prefer symbol proc to `if:` and `unless:` filter lambdas #335

Open vlad-pisanov opened 1 year ago

vlad-pisanov commented 1 year ago

Model hooks and controller filters that receive if: and unless: lambdas can be written more succinctly using symbols if the lambda consists of a single method call. This cop would enforce either style consistently based on configuration.

# bad
before_save    :log, if: -> { name_changed? }
around_destroy :baz, if: -> (user) { user.new? }
after_action   :foo, unless: -> { self.bar? }

# good
before_save    :log, if: :name_changed?
around_destroy :baz, if: :new?
after_action   :foo, unless: :bar?
koic commented 1 year ago

I think this can be proposed to the style guide first. If accepted by the style guide, it could be implemented in RuobCop Rails. So, I'll transfer this issue to the style guide repo.

pirj commented 1 year ago

A PR is welcome!

Related: https://guides.rubyonrails.org/active_record_callbacks.html#conditional-callbacks

I would be interested in how it's used in the wild, say, real-world-rails repo.

With a single predicate - fine, but what is your take on multiple ones, e.g. if: [:fresh?, :exciting?]?