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 !
Ryguy
May 3, 2011, May 03, 2011 01:54, permalink
That isn't actually setting the @opts instance variable.
class User
attr_writer :opts
def opts
@opts = @opts.is_a?(Hash) ? @opts : {}
end
end
Ryguy
May 3, 2011, May 03, 2011 01:54, permalink
That isn't actually setting the @opts instance variable.
class User
attr_writer :opts
def opts
@opts = @opts.is_a?(Hash) ? @opts : {}
end
end
Ineu
April 29, 2011, April 29, 2011 09:14, permalink
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
pahanix
May 25, 2011, May 25, 2011 13:12, permalink
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
Tyya
September 6, 2011, September 06, 2011 12:33, permalink
Last one to utilize this is a roettn egg!
green
Shortest, most aesthetic way to do this?