as a new(ru)bie I always wonder when trying to DRY such code is good or
not and why it should be (I don’t like a lot the if… else… elsif…
but sometimes it seems better for readiness… vs performances (less
code…)
If I should DRY it , any tip ?
if params[:new_title].blank?
params[:new_title] = nil
elsif params[:new_title] == “null”
params[:new_title] = “”
end
joss
Josselin wrote:
if params[:new_title].blank?
params[:new_title] = nil
elsif params[:new_title] == “null”
params[:new_title] = “”
end
params[:new_title] = if params[:new_title].blank?
nil
elsif params[:new_title] == “null”
“”
end
For reasons yet unbeknownst to you, reverse that if statement:
params[:new_title] = if params[:new_title] == “null”
“”
elsif params[:new_title].blank?
nil
end
Implicit in that if statement is an “else nil”. (Try it in IRB.) So you
don’t really need anything but the first part:
params[:new_title] = if params[:new_title] == “null”
“”
end
You can shorten even further by using the line-modifier version:
params[:new_title] = ("" if params[:new_title] == “null”)
(Parentheses are important, here. Otherwise, the if modifies the whole
line, and if not “null”, the :new_title remains unchanged.) But that’s a
little greek. Here’s another way:
params[:new_title] = params[:new_title] == ‘null’ ? ‘’ : nil
Now, there’s something very weird with the above logic, in the first
place. You might be able to reduce even more code by changing the thing
that sets :new_title. (“null”, for Ford’s sake?)
Devin
On 2/8/07, Josselin [email protected] wrote:
end
Seems to me like this should likely be an object, with
object.new_title being something like
@title.blank? ? nil : (@title == “null” ? “” : @title)
Though I also agree with Devin M. that the problem is likely to
be elsewhere (in overall structure).
Eivind.
Devin M. wrote:
elsif params[:new_title] == “null”
“”
end
Heh. Big fat bug. Right at the beginning. cough
params[:new_title] = case params[:new_title]
when ‘’: nil
when ‘null’: ‘’
else params[:new_title]
end
or:
params[:new_title] = {
‘’ => nil, ‘null’ => ‘’, params[:new_title] => params[:new_title]
}[params[:new_title]] #yikes!
Devin
On 2007-02-08 14:58:20 +0100, “Eivind E.” [email protected] said:
params[:new_title] = ""
Eivind.
Thanks to all … getting clear
Hi –
On Thu, 8 Feb 2007, Devin M. wrote:
Josselin wrote:
if params[:new_title].blank?
params[:new_title] = nil
elsif params[:new_title] == “null”
params[:new_title] = “”
end
params[:new_title] = ("" if params[:new_title] == “null”)
That doesn’t embody the same logic, though. If params[:new_title] is
neither blank? nor “null”, the original code doesn’t change it.
David