X-Git-Url: http://git.sourceforge.jp/view?a=blobdiff_plain;f=shogi_server%2Futil.rb;h=044bd2a0654f62b6b162eb0bb7ac69b2c7945afa;hb=48967e86b1a0ca5ed7c67b882757b9acd2a58655;hp=ebf8c9d1148b9f472a05bff579862052478c2993;hpb=893e6e974a00a76cab6a22bcfb45ef8bd0d1e05f;p=shogi-server%2Fshogi-server.git diff --git a/shogi_server/util.rb b/shogi_server/util.rb index ebf8c9d..044bd2a 100644 --- a/shogi_server/util.rb +++ b/shogi_server/util.rb @@ -17,8 +17,10 @@ ## 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