Refactoring: Refactorings/Introduce Class Annotation
Jump to navigation
Jump to search
Some methods have become so common that Ruby has the ability to hide them away. These behaviors can be called from the class definition. Note: This should only be done when the purpose behind the methods is clear enough to state in a single word/line.
e.g. attr_reader/writer/accessor
Mechanics
- Decide on signature of class annotation. Declare it in the appropriate class
- Convert original method into a class method. Make appropriate changes so that the method works at the class scope.
- Note: Make sure the class method is declared before the class annotation is called
- Test
- Consider using Extract Module on the class method to make annotation more prominent in class definitions.
- Test
Example
Before
class SearchCriteria
def initialize(hash)
@author_id = hash[:author_id]
@publisher_id = hash[:publisher_id]
@isbn = hash[:isbn]
end
end
After
module CustomInitializers
def hash_initializer(*attribute_names)
define_method(:initialize) do |*args|
data = args.first || {}
attribute_names.each do |attribute_name|
instance_variable_set "@*{attribute_name}", data[attribute_name]
end
end
end
end
Class.send :include, CustomInitializers
class SearchCriteria
hash_initializer :author_id, :publisher_id, :isbn
end