3
\$\begingroup\$

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
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Feb 18, 2012 at 16:14
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

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
answered Jun 28, 2015 at 15:25
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.