Refactoring: Refactorings/Replace Temp with Chain
Jump to navigation
Jump to search
A temporary object variable is used to store the result of an expression
Mechanics
- Return self from methods that you want to allow chaining from
- Test
- Remove local variable and chain the method calls
- Test
Example
Before
class Select
def options
@options ||= []
end
def add_option(arg)
options << arg
end
end
select = Select.new
select.add_option(1999)
select.add_option(2000)
select.add_option(2001)
select.add_option(2002)
After
class Select
def self.with_option(option)
select = self.new
select.options << option
select
end
def options
@options ||= []
end
def and(arg)
options << arg
self
end
end
select = Select.with_option(1999).and(2000).and(2001).and(2002)