librelist archives

« back to archive

Cleaner initialization ?

Cleaner initialization ?

From:
Peter Fitzgibbons
Date:
2012-01-19 @ 16:13
HI Folks,

I'm looking at potential code-smell.  Anyone have a "cleaner" or idiomatic
way to perform the initializations of the attr_accessors ?

  class App
    DEFAULT_WIDTH = 800
    DEFAULT_HEIGHT = 600
    DEFAULT_TITLE = "Shooes!"

    include Shoes::ElementMethods

    attr_accessor :elements, :gui_container
    attr_accessor :opts, :blk

    attr_accessor :default_width, :default_height, :default_title
    attr_accessor :width, :height, :title

    def initialize(opts={}, &blk)
      opts.stringify_keys!

      self.default_width = DEFAULT_WIDTH
      self.default_height = DEFAULT_HEIGHT
      self.default_title = DEFAULT_TITLE
      self.width = opts['width'] || self.default_width
      self.height = opts['height'] || self.default_height
      self.title = opts['title'] || self.default_title

      self.opts = opts
      self.blk = blk
  end
end

Peter Fitzgibbons
(847) 859-9550
Email: peter.fitzgibbons@gmail.com
IM GTalk: peter.fitzgibbons
IM AOL: peter.fitzgibbons@gmail.com

Re: [shoes] Cleaner initialization ?

From:
Steve Klabnik
Date:
2012-01-19 @ 16:44
This is one way. Another way looks like this:

class Foo
  def initiailize(opts={})
    opts = opts.merge(defaults)
    @some_var = opts[:some_var]
    @baz = opts[:baz]
  end

  def defaults
    {:some_var => 20, :baz => "hey"}
  end
end

Re: [shoes] Cleaner initialization ?

From:
Eric Watson
Date:
2012-01-19 @ 17:01
On Jan 19, 2012, at 10:44 AM, Steve Klabnik wrote:

> This is one way. Another way looks like this:
> 
> class Foo
>  def initiailize(opts={})
>    opts = opts.merge(defaults)
>    @some_var = opts[:some_var]
>    @baz = opts[:baz]
>  end
> 
>  def defaults
>    {:some_var => 20, :baz => "hey"}
>  end
> end

+1

although note that Steve has the merge backwards :P, and of course, you 
can make defaults a constant if you want.

class Foo

  DEFAULTS = {:some_var => 20, :baz => "hey"}

  def initialize(opts={})
    opts = DEFAULTS.merge(opts)
    @some_var = opts[:some_var]
    @baz = opts[:baz]
  end
end

1.9.3-p0 :022 > f = Foo.new(:baz => "GOO")
 => #<Foo:0x007fe52b024230 @some_var=20, @baz="GOO"> 

Re: [shoes] Cleaner initialization ?

From:
Peter Fitzgibbons
Date:
2012-01-19 @ 17:09
Thanks Steve, Eric.

Peter Fitzgibbons