diff --git a/src/compiler/ruby_generator.cc b/src/compiler/ruby_generator.cc
index e8d3c25e0b29fac6c09cab9ddc7d5ef8a6388114..c5c588473638d5628278a1c25ca35c8e466f14d4 100644
--- a/src/compiler/ruby_generator.cc
+++ b/src/compiler/ruby_generator.cc
@@ -126,7 +126,13 @@ string GetServices(const FileDescriptor* file) {
   StringOutputStream output_stream(&output);
   Printer out(&output_stream, '$');
 
-  // Always write out a file header.
+  // Don't write out any output if there no services, to avoid empty service
+  // files being generated for proto files that don't declare any.
+  if (file->service_count() == 0) {
+    return output;
+  }
+
+  // Write out a file header.
   map<string, string> header_comment_vars = ListToDict({
         "file.name", file->name(),
         "file.package", file->package(),
@@ -134,9 +140,6 @@ string GetServices(const FileDescriptor* file) {
   out.Print("# Generated by the protocol buffer compiler.  DO NOT EDIT!\n");
   out.Print(header_comment_vars,
             "# Source: $file.name$ for package '$file.package$'\n");
-  if (file->service_count() == 0) {
-    return output;
-  }
 
   out.Print("\n");
   out.Print("require 'grpc'\n");
diff --git a/src/compiler/ruby_plugin.cc b/src/compiler/ruby_plugin.cc
index 62229f921747f89a625af878cd9df13e6fd2ebe1..c1748cfaeb0cba48a86503449b52124a8a7bcf2d 100644
--- a/src/compiler/ruby_plugin.cc
+++ b/src/compiler/ruby_plugin.cc
@@ -55,16 +55,19 @@ class RubyGrpcGenerator : public google::protobuf::compiler::CodeGenerator {
                 const string& parameter,
                 google::protobuf::compiler::GeneratorContext* context,
                 string* error) const override {
+    string code = grpc_ruby_generator::GetServices(file);
+    if (code.size() == 0) {
+      return true;  // don't generate a file if there are no services
+    }
+
     // Get output file name.
     string file_name;
     if (!grpc_ruby_generator::ServicesFilename(file, &file_name)) {
       return false;
     }
-
     std::unique_ptr<google::protobuf::io::ZeroCopyOutputStream> output(
         context->Open(file_name));
     google::protobuf::io::CodedOutputStream coded_out(output.get());
-    string code = grpc_ruby_generator::GetServices(file);
     coded_out.WriteRaw(code.data(), code.size());
     return true;
   }