rubocop-dynamic_methods
rubocop-dynamic_methodsv0.1.0MIT
RuboCop cops that rewrite dynamically defined methods as plain defs you can search for.
Install
gem install rubocop-dynamic_methodsA reader, a coding agent first and a person second, searches for def paid? and finds nothing when paid? comes from define_method or a string eval.
rubocop-dynamic_methods is a RuboCop plugin whose cops find those methods and write them as plain defs.
The autocorrection writes a def only when Ruby would define the same method.
Otherwise the offense says why, so whoever writes the def next knows what to write.
Features
Section titled “Features”DynamicMethods/DefineMethod. Findsdefine_methodanddefine_singleton_method, and autocorrects them todef nameanddef self.name.DynamicMethods/StringEval. Findsclass_eval,module_eval,instance_eval, andevalwith a string, and autocorrects them to the defs the string holds.DynamicMethods/MethodMissingandDynamicMethods/Delegation. Reportdef method_missing, anddelegate,delegate_missing_to,def_delegator, anddef_delegators. Neither autocorrects, andDelegationis disabled by default.- Exact or not at all. A rewrite keeps the same names, parameters, bodies, and visibility. An
eachover a literal Array or Hash, or over a constant the same body sets once to one before the loop, becomes one def per value. - A reason to act on. When the cop cannot be sure, the offense names the cause, such as
Not autocorrected: `ELEMENTS` is not frozen, and the code stays as it is.
How an agent uses it
Section titled “How an agent uses it”- Run
rubocop -A --only DynamicMethodson the code. - Read each
[Corrected]line, and check the defs it wrote. - For each offense that was not corrected, read the reason and write the def by hand.
The autocorrection is unsafe in RuboCop’s sense, because it trusts that define_method, class_eval, and Array#each are Ruby’s own. Run it with rubocop -A.
Getting started
Section titled “Getting started”The plugin needs RuboCop 1.72 or later and Ruby 3.2 or later.
# Gemfilegem "rubocop-dynamic_methods", require: falseplugins: - rubocop-dynamic_methodsrubocop -A --only DynamicMethods order.rb