2008-07-30 15:47:12 -04:00
|
|
|
class Factory
|
|
|
|
|
2008-12-11 15:54:33 -05:00
|
|
|
class << self
|
|
|
|
attr_accessor :aliases #:nodoc:
|
|
|
|
end
|
2008-07-30 15:47:12 -04:00
|
|
|
self.aliases = [
|
|
|
|
[/(.*)_id/, '\1'],
|
|
|
|
[/(.*)/, '\1_id']
|
|
|
|
]
|
|
|
|
|
2009-02-17 16:38:15 -05:00
|
|
|
# Defines a new alias for attributes.
|
2008-07-30 15:47:12 -04:00
|
|
|
#
|
|
|
|
# Arguments:
|
2009-02-17 16:38:15 -05:00
|
|
|
# * pattern: +Regexp+
|
|
|
|
# A pattern that will be matched against attributes when looking for
|
|
|
|
# aliases. Contents captured in the pattern can be used in the alias.
|
|
|
|
# * replace: +String+
|
|
|
|
# The alias that results from the matched pattern. Captured strings can
|
2010-06-23 04:24:47 +08:00
|
|
|
# be substituted like with +String#sub+.
|
2008-07-30 15:47:12 -04:00
|
|
|
#
|
|
|
|
# Example:
|
2010-06-07 15:51:18 -04:00
|
|
|
#
|
2008-07-30 15:47:12 -04:00
|
|
|
# Factory.alias /(.*)_confirmation/, '\1'
|
2009-02-17 16:38:15 -05:00
|
|
|
#
|
|
|
|
# factory_girl starts with aliases for foreign keys, so that a :user
|
|
|
|
# association can be overridden by a :user_id parameter:
|
|
|
|
#
|
|
|
|
# Factory.define :post do |p|
|
|
|
|
# p.association :user
|
|
|
|
# end
|
|
|
|
#
|
|
|
|
# # The user association will not be built in this example. The user_id
|
|
|
|
# # will be used instead.
|
|
|
|
# Factory(:post, :user_id => 1)
|
2008-07-30 15:47:12 -04:00
|
|
|
def self.alias (pattern, replace)
|
|
|
|
self.aliases << [pattern, replace]
|
|
|
|
end
|
|
|
|
|
|
|
|
def self.aliases_for (attribute) #:nodoc:
|
|
|
|
aliases.collect do |params|
|
|
|
|
pattern, replace = *params
|
|
|
|
if pattern.match(attribute.to_s)
|
|
|
|
attribute.to_s.sub(pattern, replace).to_sym
|
|
|
|
else
|
|
|
|
nil
|
|
|
|
end
|
|
|
|
end.compact << attribute
|
|
|
|
end
|
|
|
|
|
|
|
|
end
|