Refactoring: Refactorings/Move Eval from Runtime to Parse Time
Jump to navigation
Jump to search
Calling Kernel#eval is always expensive from a performance standpoint. If performance is necessary, move the eval call to parse-time instead of calling it from run-time
Mechanics
- Expand the scope of the string being eval'd
- Test
Example
Before
class Person
def self.attr_with_default(options)
options.each_pair do |attribute, default_value|
define_method attribute do
eval "@#{attribute} ||== #{default_value}"
end
end
end
attr_with_default :emails => "[]", :employee_number => "EmployeeNumberGenerator.next"
end
After
class Person
def self.attr_with_default(options)
options.each_pair do |attribute, default_value|
eval "define_method attribute do
@#{attribute} ||== #{default_value}
end"
end
end
attr_with_default :emails => "[]", :employee_number => "EmployeeNumberGenerator.next"
end