Ruby metaprogramming is worth noting.
Avoid infinite loop metaprogramming.
Do not confuse the core class (do not use monkey patch) when writing a function library ).
It is best to use the code block form in the string interpolation form.
When you use string interpolation, _ FILE _ and _ LINE __are always provided to make your backtracking meaningful.
class_eval 'def use_relative_model_naming?; true; end', __FILE__, __LINE__
Define_method is best to use class_eval {def ...}
When class_eval (or other eval) and string interpolation are used, add a comment block to display it during insertion (this is my practice in rails code ):
# from activesupport/lib/active_support/core_ext/string/output_safety.rb UNSAFE_STRING_METHODS.each do |unsafe_method| if 'String'.respond_to?(unsafe_method) class_eval <<-EOT, __FILE__, __LINE__ + 1 def #{unsafe_method}(*args, &block) # def capitalize(*args, &block) to_str.#{unsafe_method}(*args, &block) # to_str.capitalize(*args, &block) end # end def #{unsafe_method}!(*args) # def capitalize!(*args) @dirty = true # @dirty = true super # super end # end EOT end end
Avoid using method_missing in metaprogramming, which makes tracing very troublesome. This habit is not listed in # methods. misspelling methods may also work silently, such as nukes. launch_state = false. Use the delegate, proxy, or define_method. If so, use method_missing,
Make sure respond_to_missing is also defined?
Just capture the first-defined method, such as find_by _ *-the better your code (assertive.
At the end of the statement, super is called.
Delegate to a definite, non-magic method:
# bad def method_missing?(meth, *args, &block) if /^find_by_(?<prop>.*)/ =~ meth # ... lots of code to do a find_by else super end end # good def method_missing?(meth, *args, &block) if /^find_by_(?<prop>.*)/ =~ meth find_by(prop, *args, &block) else super end end # best of all, though, would to define_method as each findable attribute is declared