Avoid the metaprogramming of infinite loops.
Do not confuse the core class when writing a function library (do not use monkey patch).
code block forms are best used in string interpolation forms.
When you use a string interpolation form, always provide __file__ and __line__, making your backtracking meaningful.
Class_eval ' Def use_relative_model_naming?; True End ', __file__, __line__
Define_method best Use class_eval{def ...}
When using Class_eval (or other eval) and string interpolation, add a comment block to display when inserting (this is what I learned from the 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 Capita Lize (*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 # EOT End
Avoid using method_missing in metaprogramming, which makes backtracking cumbersome, which is not listed in #methods, and the misspelled method may also work silently, such as Nukes.launch_state = False. Consider using a delegate, an agent or a define_method, if you must, use method_missing,
Make sure you also define the respond_to_missing?
Capturing only the first word is a well defined method, like find_by_*― makes your code more positive (assertive).
Call Super at the end of the statement
Delegate to certain, not magical methods:
# bad
def method_missing? ( Meth, *args, &block)
if/^find_by_ (? <prop>.*)/=~ meth
# ... lots of code to do a find_by
else
s Uper
End
# good
def method_missing? ( Meth, *args, &block)
if/^find_by_ (? <prop>.*)/=~ meth
(find_by, prop, *args)
Else
Super End and
# Best of all
, though, would to Define_method as each findable the attribute is declared