Forum: Ruby suggestions needed to go DRY

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
gaurav bagga (Guest)
on 2007-04-16 09:28
(Received via mailing list)
Hi All,

     Recently I was in a situation where I needed to add a functionality
to
a method but I couldn't change the method signature as people in my team
were using the same method at many places.I joined the team late so it
was
not envisioned that my part will bring in need for few changes.I
couldn't
create a new method as
it wont be dry.The case was I needed to merge few key,value pairs in
side
the hash present in method.These were not same all the time.

  the method was-->

  def doThing  var1,var2
    html_options #already defined the basic things needed for
functionality
in this hash
  end

  I made changes within the method  -->

 def doThing var1,var2
   html_options.merge! :onclick => yield if block_given?
  end

 so calling it doThing("one","two") {"methodCalledOnClick()"} did the
trick
 other people were happy using it doThing "one","two"

 I hope I was able to explain my situation.
 I'll appreciate if you give few inputs how you people would have done
the
same thing or guide me to do this in a better fashion.
Brian C. (Guest)
on 2007-04-16 09:48
(Received via mailing list)
On Mon, Apr 16, 2007 at 02:27:56PM +0900, gaurav bagga wrote:
>   html_options.merge! :onclick => yield if block_given?
>  end
>
> so calling it doThing("one","two") {"methodCalledOnClick()"} did the trick
> other people were happy using it doThing "one","two"

Another way is to have an optional argument:

def doThing(var1, var2, opts={})
  html_options.merge!(opts)
end

or:

def doThing(var1, var2, opts=nil)
  html_options.merge!(opts) if opts
end
Martin DeMello (Guest)
on 2007-04-16 11:22
(Received via mailing list)
On 4/16/07, gaurav bagga <removed_email_address@domain.invalid> wrote:
>
>  def doThing var1,var2
>    html_options.merge! :onclick => yield if block_given?
>   end
>
>  so calling it doThing("one","two") {"methodCalledOnClick()"} did the trick
>  other people were happy using it doThing "one","two"

This scales slightly better (think of adding several options):

def doThing var1, var2
  yield html_options
  ...
end

use as

doThing(var1, var2) {|opts|
  opts[:onclick] =foo
  opts[:css] = bar
  ...
}

martin
gaurav bagga (Guest)
on 2007-04-17 08:41
(Received via mailing list)
Thanks Brian and Martin for feedback
That was nice

Martin your idea for scalability I liked
Brian optional arguments taught me something new I overlooked that

Regards
Gaurav
This topic is locked and can not be replied to.