1
0
Fork 0
mirror of https://github.com/thoughtbot/factory_bot.git synced 2022-11-09 11:43:51 -05:00
thoughtbot--factory_bot/lib/factory_bot/aliases.rb
Aqualon 893eb67bbb
Use match? in FactoryBot#aliases_for to save allocations (#1457)
FactoryBot relies on ruby >= 2.5, so we can use Regexp#match? that does not allocate MatchData

Allocations measured with heap-profiler gem in an internal test suite with 7497 examples and 149470 calls to aliases_for:

allocated memory by file
-----------------------------------
    59.79 MB  factory_bot-6.1.0/lib/factory_bot/aliases.rb
    38.27 MB  factory_bot-6.1.0/lib/factory_bot/aliases.rb

allocated objects by file
-----------------------------------
    896880  factory_bot-6.1.0/lib/factory_bot/aliases.rb
    597940  factory_bot-6.1.0/lib/factory_bot/aliases.rb
2021-09-09 21:43:47 -04:00

18 lines
344 B
Ruby

module FactoryBot
class << self
attr_accessor :aliases
end
self.aliases = [
[/(.+)_id/, '\1'],
[/(.*)/, '\1_id']
]
def self.aliases_for(attribute)
aliases.map { |(pattern, replace)|
if pattern.match?(attribute)
attribute.to_s.sub(pattern, replace).to_sym
end
}.compact << attribute
end
end