I figure there is a better way that I should be doing this:
if !db.collection_names.include?("reports".to_s)
db.create_collection("reports")
end
if !db.collection_names.include?("days".to_s)
db.create_collection("days")
end
if !db.collection_names.include?("users".to_s)
db.create_collection("users")
end
1 Answer 1
Well, firstly: "string".to_s
is entirely redundant. That's already a String
, so converting it again is just wasting your (processor's) time.
Secondly, writing if
blocks with just one line and no else
wastes a good deal of vertical real estate. I'd recommend that instead of
if condition
statement
end
you should write
statement if condition
Ruby has unless
as the opposite to if
, and when you find yourself writing if !...
, it's better to use unless ...
instead. This is mostly because of convention -- Ruby programmers use unless
a lot more, so it's quicker to parse.
As for shortening the method calls themselves, you could just pass strict: false
in with the name, so each individual call becomes more like this:
db.create_collection('name', strict: false)
Then you don't need the condition at all.
Then, since you have three objects on which you want to perform the same action, you can put them in an array:
['reports', 'days', 'users']
(or use the fancier %w{ reports days users }
, like I do below, but you'll want to read up on its gotchas first)
Then we can loop through that array:
%w{ reports days users }.each do |name|
#...
end
And in place of #...
we put the code to create the table:
db.create_collection(name, strict: false)
Or, if you don't want to rely on swallowing errors:
db.create_collection(name) unless db.collection_names.include?(name)
If we put that all together, it becomes this:
%w{ reports days users }.each do |name|
db.create_collection(name) unless db.collection_names.include?(name)
end
Now, to add a collection, all you have to do is add it to the list. For example, if you wanted to add one called "years", add years
in to the %w
:
%w{ reports days users years }.each do |name|
db.create_collection(name) unless db.collection_names.include?(name)
end