OSDN Git Service

../shogi_server.rb, ../shogi_server/util.rb: Refactored mkdir_for to Mkdir.mkdir_for.
[shogi-server/shogi-server.git] / shogi_server / util.rb
index ebf8c9d..044bd2a 100644 (file)
 ## along with this program; if not, write to the Free Software
 ## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
+require 'date'
 require 'fileutils'
 require 'pathname'
+require 'thread'
 
 module ShogiServer
 
@@ -67,4 +69,54 @@ module ShogiServer
   end
   module_function :is_writable_file?
 
+  # Convert a DateTime insntace to a Time instance.
+  #
+  def datetime2time(dt)
+    return Time.mktime dt.year, dt.month, dt.day, dt.hour, dt.min, dt.sec
+  end
+  module_function :datetime2time
+
+  # Convert a Time instance to a DateTime instance
+  #
+  def time2datetime(time)
+    return DateTime.new(time.year, time.mon, time.mday,
+                        time.hour, time.min, time.sec)
+  end
+  module_function :time2datetime
+
+  # Parse string representing a day-of-week and return a coresponding
+  # integer value: 1 (Monday) - 7 (Sunday)
+  #
+  def parse_dow(str)
+    index = Date::DAYNAMES.index(str) || Date::ABBR_DAYNAMES.index(str)
+    return nil if index.nil?
+    return index == 0 ? 7 : index
+  end
+  module_function :parse_dow
+
+  # Mkdir in a thread-safe way.
+  #
+  class Mkdir
+    @@mutex = Mutex.new
+
+    # Return true if a directory is successfully created or a directory
+    # exists already; false otherwise.
+    #
+    # @param path a directory name of a path to be created. For example,
+    # given /hoge/hoo/foo.txt, aim to create /hoge/hoo.
+    def Mkdir.mkdir_for(path)
+      unless FileTest.directory?(File.dirname(path))
+        @@mutex.synchronize do
+          unless FileTest.directory?(File.dirname(path))
+            begin
+              FileUtils.mkdir_p File.dirname(path)
+            rescue
+              return false
+            end
+          end
+        end # mutex
+      end
+      return true
+    end
+  end # class Mkdir
 end