I thought that this question ( How to do attr_accessor_with_default in ruby? ) answered my question, but I'm not using ActiveRecord and after_initialize depends on it.
What's the Ruby best practice for implementing a default value for an attr_accessor
? Is this the closest thing to documentation about it? Should I stop using attr_accessor
since it is private?
You can assign the default value using the DefaultValueAttribute attribute, as shown below.
In JavaScript, function parameters default to undefined . However, it's often useful to set a different default value. This is where default parameters can help. In the past, the general strategy for setting defaults was to test parameter values in the function body and assign a value if they are undefined .
class Foo
# class-level instance variable
# setting initial value (optional)
@class_var = 42
# making getter/setter methods on the class itself
class << self
attr_accessor :class_var
end
# instance-level variable getter/setter methods
attr_accessor :inst_var
def initialize
# setting initial value (optional)
@inst_var = 17
end
end
p Foo.class_var
#=> 42
Foo.class_var = 99
p Foo.class_var
#=> 99
f1 = Foo.new
f2 = Foo.new
f2.inst_var = 1
p [f1.inst_var, f2.inst_var]
#=> [17,1]
Just to clarify some of the code snippets above that might be misleading, the best way to set a default value on a Ruby instance variable is NOT the same behavior as PHP or Python.
The simple solution is to set default values for your instance variables is to set them inside the initialize()
method:
class MyClass
attr_accessor :foo
# @foo = 'This is totally ignored! Do not try to set a default value here!'
def initialize
@foo = 'default'
end
end
x = MyClass.new
print x.foo # tada!
@Phrogz gave a nice solution, but you should know more about it.
Here you make a class-level instance variable
, which is not really a class variable, but who cares, because after you initialize a real class variable with the same name, you lose an old reference.
To inspect the fakeness, use the above code, but with an array:
class Foo
@class_var = [42]
class << self
attr_accessor :class_var
end
end
b = [Foo.class_var]
Foo.class_var = 69
p b # still [[42]]
And you are going to get a problem, when trying to get the variable via @@
which was supposed for a real class variable.
class Bar
@class_var = [42]
class << self
attr_accessor :class_var
end
def biz
self.class.class_var
end
def baz
@@class_var
end
end
p Bar.new.biz # self.class. is kinda a way to emulate the reference from outside
p Bar.new.baz # and exception, because you don't really have a class variable defined yet!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With