Skip to content

Commit

Permalink
Use attr_readers in association declaration
Browse files Browse the repository at this point in the history
This commit separates the factory name from the overrides on initialize,
then uses attr_readers throughout instead of manipulating instance
variables.

This is a bit cleaner, and will make it easier to reused the
factory_name and overrides in a future code change.
  • Loading branch information
composerinteralia committed Jun 22, 2020
1 parent a7379af commit f223c7d
Showing 1 changed file with 12 additions and 4 deletions.
16 changes: 12 additions & 4 deletions lib/factory_bot/declaration/association.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ def initialize(name, *options)
super(name, false)
@options = options.dup
@overrides = options.extract_options!
@factory_name = @overrides.delete(:factory) || name
@traits = options
end

Expand All @@ -21,18 +22,25 @@ def ==(other)

private

attr_reader :factory_name, :overrides, :traits

def build
ensure_factory_is_not_a_declaration!

factory_name = @overrides[:factory] || name
[Attribute::Association.new(name, factory_name, [@traits, @overrides.except(:factory)].flatten)]
[
Attribute::Association.new(
name,
factory_name,
[traits, overrides].flatten
)
]
end

def ensure_factory_is_not_a_declaration!
if @overrides[:factory].is_a?(Declaration)
if factory_name.is_a?(Declaration)
raise ArgumentError.new(<<~MSG)
Association '#{name}' received an invalid factory argument.
Did you mean? 'factory: :#{@overrides[:factory].name}'
Did you mean? 'factory: :#{factory_name.name}'
MSG
end
end
Expand Down

0 comments on commit f223c7d

Please sign in to comment.