Sunday, 15 May 2016

ruby on rails - How can I create unique strings (with no numbers) with factory girl?



Or is an external gem necessary to generate random and unique usernames maybe?




Here's my current factory:



factory :user_4 do
sequence(:id) { |n| n }
sequence(:first_name) { |n| "Gemini" + n.to_s }
sequence(:last_name) { |n| "Pollux" + n.to_s }
sequence(:profile_name) { |n| "GeminiPollux" + n.to_s }
sequence(:email) { |n| "geminipollus" + n.to_s + "@hotmail.co.uk" }
end



Using the sequence method works for the id, profile_name and email, but my REGEX validations mean that the first name and last name are automatically invalid, because they have a digit in them. Nothing to do with the uniqueness.



So how should I create these unique names?


Answer



There are infinite possible solutions to generate a random string without relying on third party gems.



Here's one




('a'..'z').to_a.shuffle.join
# => "sugrjtyoiqlbxkzcfnawdhpevm"


Example



factory :user_4 do
sequence(:id) { |n| n }
first_name { "Gemini" + random_name }
# ...

end

def random_name
('a'..'z').to_a.shuffle.join
end


If the random factor is too low, you can increase the complexity.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...