Ba665f86f90a1982af7b9c857418fcdb

Shortest, most aesthetic way to do this?

class User
  attr_writer :opts
  def opts
    if instance_variable_defined?(:@opts) && @opts.is_a?(Hash)
      @opts
    else
      @opts = Hash.new
    end
  end
end 

my_user = User.new
p my_user.opts # => {}
p my_user.opts = Array.new # Trying to set opts as an Array...
p my_user.opts # => {}     # But we won't let that fly.

Refactorings

No refactoring yet !

Ba665f86f90a1982af7b9c857418fcdb

Ryguy

May 3, 2011, May 03, 2011 01:54, permalink

No rating. Login to rate!

That isn't actually setting the @opts instance variable.

class User
  attr_writer :opts
  def opts
    @opts = @opts.is_a?(Hash) ? @opts : {}
  end 
end
Ba665f86f90a1982af7b9c857418fcdb

Ryguy

May 3, 2011, May 03, 2011 01:54, permalink

No rating. Login to rate!

That isn't actually setting the @opts instance variable.

class User
  attr_writer :opts
  def opts
    @opts = @opts.is_a?(Hash) ? @opts : {}
  end 
end
98e418d97d7c68ecb8db574750ae3f50

Ineu

April 29, 2011, April 29, 2011 09:14, permalink

No rating. Login to rate!

No need to use 'if' as instance variable is nil by default (which also gives false for 'is_a? Hash')

class User
  attr_writer :opts
  def opts
    @opts.is_a?(Hash) ? @opts : {}
  end 
end
A74c34f1043b833b1fcc86ce9f3521ee

pahanix

May 25, 2011, May 25, 2011 13:12, permalink

No rating. Login to rate!

It's better to raise ArgumentError when trying to assign not Hash to opts. it's more clear and safe.

P.S. If you use ActiveRecord don't use #initialize. Use #after_initialize callback
In some cases objects created using AcriveRecord::Base#find (using #allocate) never run #initialize!

http://blog.dalethatcher.com/2008/03/rails-dont-override-initialize-on.html
http://www.3hv.co.uk/blog/2009/06/03/constructors-in-ruby-are-not-guaranteed-to-be-called/
http://web.archive.org/web/20080527003425/http://whytheluckystiff.net/articles/rubyOneEightOh.html

class User
  attr_reader :opts

  def initialize
    @opts = {}
  end
  
  def opts=(value)
    raise(ArgumentError, "User#opts= should be a Hash") unless value.is_a?(Hash)
    @opts = value
  end
end
D5d94696ddf22753581097dd22f8d1eb

Tyya

September 6, 2011, September 06, 2011 12:33, permalink

No rating. Login to rate!

Last one to utilize this is a roettn egg!

green
D5d94696ddf22753581097dd22f8d1eb

Tyya

September 6, 2011, September 06, 2011 12:34, permalink

No rating. Login to rate!

Last one to utilize this is a roettn egg!

green
D5d94696ddf22753581097dd22f8d1eb

Tyya

September 6, 2011, September 06, 2011 12:34, permalink

No rating. Login to rate!

Last one to utilize this is a roettn egg!

green

Your refactoring





Format Copy from initial code

or Cancel