Refactor mode code

This commit is contained in:
Scott Taylor 2009-09-30 03:44:42 -04:00
parent 6d44186cf7
commit 731122a1ac

View File

@ -11,6 +11,22 @@ module FakeFS
APPEND_READ_WRITE = "a+" APPEND_READ_WRITE = "a+"
] ]
FILE_CREATION_MODES = MODES - [READ_ONLY, READ_WRITE]
READ_ONLY_MODES = [
READ_ONLY
]
WRITE_ONLY_MODES = [
WRITE_ONLY,
APPEND_WRITE_ONLY
]
TRUNCATION_MODES = [
WRITE_ONLY,
READ_WRITE_TRUNCATE
]
def self.extname(path) def self.extname(path)
RealFile.extname(path) RealFile.extname(path)
end end
@ -100,14 +116,14 @@ module FakeFS
end end
attr_reader :path attr_reader :path
def initialize(path, mode = READ_ONLY, perm = nil)
check_mode(mode)
def initialize(path, mode = READ_ONLY, perm = nil)
@path = path @path = path
@mode = mode @mode = mode
@file = FileSystem.find(path) @file = FileSystem.find(path)
@open = true @open = true
check_valid_mode
file_creation_mode? ? create_missing_file : check_file_existence! file_creation_mode? ? create_missing_file : check_file_existence!
truncate_file if truncation_mode? truncate_file if truncation_mode?
end end
@ -119,6 +135,7 @@ module FakeFS
def read def read
raise IOError, 'closed stream' unless @open raise IOError, 'closed stream' unless @open
raise IOError, 'not opened for reading' if write_only? raise IOError, 'not opened for reading' if write_only?
@file.content @file.content
end end
@ -151,22 +168,30 @@ module FakeFS
end end
end end
def read_only? def check_valid_mode
@mode == READ_ONLY if !mode_in?(MODES)
raise ArgumentError, "illegal access mode #{@mode}"
end
end end
def file_creation_modes def read_only?
MODES - [READ_ONLY, READ_WRITE] mode_in? READ_ONLY_MODES
end end
def file_creation_mode? def file_creation_mode?
file_creation_modes.include?(@mode) mode_in? FILE_CREATION_MODES
end end
def check_mode(mode) def write_only?
if !MODES.include?(mode) mode_in? WRITE_ONLY_MODES
raise ArgumentError, "illegal access mode #{mode}"
end end
def truncation_mode?
mode_in? TRUNCATION_MODES
end
def mode_in?(list)
list.include?(@mode)
end end
def create_missing_file def create_missing_file
@ -175,16 +200,8 @@ module FakeFS
end end
end end
def write_only?
@mode == WRITE_ONLY || @mode == APPEND_WRITE_ONLY
end
def truncate_file def truncate_file
@file.content = "" @file.content = ""
end end
def truncation_mode?
@mode == READ_WRITE_TRUNCATE || @mode == WRITE_ONLY
end
end end
end end