Skip to content

Commit

Permalink
Split Candidates#each in few methods
Browse files Browse the repository at this point in the history
  • Loading branch information
novikserg authored and parndt committed Jan 25, 2017
1 parent 54cbe32 commit dac59ef
Showing 1 changed file with 21 additions and 12 deletions.
33 changes: 21 additions & 12 deletions lib/friendly_id/candidates.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,26 +10,35 @@ class Candidates

def initialize(object, *array)
@object = object
@candidates = to_candidate_array(object, array.flatten(1))
@raw_candidates = to_candidate_array(object, array.flatten(1))
end

# Visits each candidate, calls it, passes it to `normalize_friendly_id` and
# yields any wanted and unreserved slug candidates.
def each(*args, &block)
pre_candidates = @candidates.map do |candidate|
@object.normalize_friendly_id(candidate.map(&:call).join(' '))
end.select {|x| wanted?(x)}
return candidates unless block_given?
candidates.each{ |candidate| yield candidate }
end

unless pre_candidates.all? {|x| reserved?(x)}
pre_candidates.reject! {|x| reserved?(x)}
end
private

return pre_candidates unless block_given?
def candidates
@candidates ||= begin
candidates = normalize(@raw_candidates)
filter(candidates)
end
end

pre_candidates.each {|x| yield x}
def normalize(candidates)
candidates.map do |candidate|
@object.normalize_friendly_id(candidate.map(&:call).join(' '))
end.select {|x| wanted?(x)}
end

private
def filter(candidates)
unless candidates.all? {|x| reserved?(x)}
candidates.reject! {|x| reserved?(x)}
end
candidates
end

def to_candidate_array(object, array)
array.map do |candidate|
Expand Down

0 comments on commit dac59ef

Please sign in to comment.