Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I refactor these conditionals in my ruby class?

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?

like image 617
Amit Erandole Avatar asked Mar 03 '26 13:03

Amit Erandole


2 Answers

def self.file_usable?
  @@filepath and File.exists?(@@filepath) and File.readable?(@@filepath) and File.writable?(@@filepath)
end
like image 57
megas Avatar answered Mar 06 '26 00:03

megas


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
like image 29
tokland Avatar answered Mar 06 '26 00:03

tokland