-
-
Save paneq/1082096 to your computer and use it in GitHub Desktop.
require 'test/unit' | |
class KeyTest < Test::Unit::TestCase | |
def test_key | |
object = Object.new | |
assert_equal(:submit, object_key(object)) | |
def object.persisted?; true end | |
assert_equal(:update, object_key(object)) | |
def object.persisted?; false end | |
assert_equal(:create, object_key(object)) | |
end | |
end |
def object_key | |
if @object && @object.respond_to?(:persisted?) | |
@object.persisted? ? :update : :create | |
else | |
:submit | |
end | |
end |
def object_key | |
return :submit unless @object && @object.respond_to?(:persisted?) | |
return @object.persisted? ? :update : :create | |
end |
def object_key | |
# assume that nil does not respond to :persisted? and if it does, then respect that | |
return :submit unless @object.respond_to?(:persisted?) | |
return @object.persisted? ? :update : :create | |
end |
def object_key | |
if @object && @object.respond_to?(:persisted?) && @object.persisted? | |
:update | |
elsif @object && @object.respond_to?(:persisted?) | |
:create | |
else | |
:submit | |
end | |
end |
def object_key | |
return :submit if ! persistable?(@object) | |
return :update if ! @object.persisted? | |
return :create if @object.persisted? | |
end | |
def persistable?(object) | |
object && object.respond_to?(:persisted?) | |
end |
def object_key | |
return :submit unless @object.respond_to?(:persisted?) | |
return :update if @object.persisted? | |
return :create | |
end |
persisted = @object.respond_to?(:persisted?) ? @object.persisted? : nil | |
case persisted | |
when true then :update | |
when false then :create | |
else :submit | |
end |
def object_key(object) | |
object.persisted? ? :update : :create | |
rescue; :submit | |
end |
def object_key(object) | |
object.persisted? ? :update : :create rescue NoMethodError :submit | |
end |
V06. In 05 the ! are easy to oversee.
Both follow a beautifull because they are most readible
After one day of thinking I also prefer v05 with the same remark as pzol added - ! is easy to oversee. Maybe using "not" keyword would help with readability.
What do you think about v08 - using exceptions?
You can also write as:
return :submit unless persistable?(@object)
return :update unless @object.persisted?
return :create
I'm using Ruby since 2004 and every time I see "unless" in the code I have to stop, compile it to "if not", think and then go on ;)
Premature optimization...
I have seen this flow argument many times - why exactly exceptions can't be used when controlling the flow?
The example above is not the best one as it catches NoMethodError which is a bit extrem, but sometimes it's nice to raise ProductNotAvailable. If you're not using exceptions then you end up with lots of ifs on the client side. I prefer the "Tell, Don't Ask" approach.
I bet on v05. Clean, beauty and most readable.