def self.valid?(key)
h=find_by_key(key)
if !h.nil?
total = h.total
real = h.invitation_details_count
(real < total) ? true : false
else
false
end
end
Refactorings
No refactoring yet !
Dan Kubb
April 13, 2008, April 13, 2008 04:26, permalink
This refactoring uses a guard clause to short-circuit the method at the beginning. Guard clauses are a clean way to exit out of a method if some condition isn't immediately met. Also since the comparison statement returns true/false, there's no need to use a ternary operator to explicitly return true or false.
def self.valid?(key) return false unless h = find_by_key(key) h.invitation_details_count < h.total end
Jeremy Weiskotten
April 21, 2008, April 21, 2008 15:04, permalink
Here's a one-liner...
def self.valid?(key) !(h = find_by_key(key)).nil? && h.invitation_details_count < h.total end
Adkron
April 22, 2008, April 22, 2008 03:03, permalink
Like Jeremy on I like my statements in the positive. I don't like a lot of ! if I can avoid them. So you add a little De Morgan's Law and you get the following.
def self.valid?(key) (h = find_by_key(key)).nil? || h.invitation_details_count >= h.total end
Adkron
April 22, 2008, April 22, 2008 03:08, permalink
Wait that doesn't work. I had the law messed up. De Morgan's LAw is: "~(p and q)" is logically equivalent to "(~p) or (~q)" . I think I may have made too far a leap. If I wanted to apply the law I would have had to put a ! in front of the whole thing. So I still would have my !. Sad sad me.
def self.valid?(key) !((h = find_by_key(key)).nil? || h.invitation_details_count >= h.total) end
mitch
May 17, 2008, May 17, 2008 14:22, permalink
I know that this is an old thread but I was just confused by all the "!(something.nil?)" refactorings. It think the logic is: If (the key is there) and (the invitation_details_count is less than the total) then it's valid.
def self.valid?(key) (h = find_by_key(key)) && (h.invitation_details_count < h.total) end
hacksignal.myopenid.com
May 23, 2008, May 23, 2008 20:01, permalink
if you have controller method
if YourClass.valid(key)?
something = YourClass.find(key)
.....
end
You can still work with returning true/false or just have the method return your object if key is valid.
#returns true/false def self.valid?(key) !find_by_key(key,:conditions=>['invitation_details_count < total']).nil? end #or returning your object def self.find_valid_key(key) find_by_key(key,:conditions=>['invitation_details_count < total']) end
Any idea about better code?