Here is my method. It checks if the file is usable. How do I dry this out?
@@filepath = nil
def self.file_usable?
return false unless @@filepath
return false unless File.exists?(@@filepath)
return false unless File.readable?(@@filepath)
return false unless File.writable?(@@filepath)
return true
end
Should I be using some kind of loop?
def self.file_usable?
@@filepath and File.exists?(@@filepath) and File.readable?(@@filepath) and File.writable?(@@filepath)
end
I wouldn't do it this way, but since you asked "to just refactor all these methods action on the same variable"...
def self.file_usable?
@@filepath && [:exists?, :readable?, :writable?].all? { |m| File.send(m, @@filepath) }
end
This may be useful if you programatically need to decide which methods must be checked. If that's an isolated function, I'd write:
def self.file_usable?
f = @@filepath
f && File.exists?(f) && File.readable?(f) && File.writable?(f)
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With