method
cattr_writer
v3.2.8 -
Show latest stable
-
1 note -
Class: Class
- 1.0.0
- 1.1.6
- 1.2.6
- 2.0.3
- 2.1.0 (0)
- 2.2.1 (0)
- 2.3.8 (0)
- 3.0.0 (0)
- 3.0.9 (0)
- 3.1.0 (0)
- 3.2.1 (0)
- 3.2.8 (38)
- 3.2.13 (0)
- 4.0.2 (0)
- 4.1.8
- 4.2.1
- 4.2.7
- 4.2.9
- 5.0.0.1
- 5.1.7
- 5.2.3
- 6.0.0
- 6.1.3.1
- 6.1.7.7
- 7.0.0
- 7.1.3.2
- 7.1.3.4
- What's this?
cattr_writer(*syms)
public
Defines a class attribute if it’s not defined and creates a writer method to allow assignment to the attribute.
class Person cattr_writer :hair_colors end Person.hair_colors = [:brown, :black] Person.class_variable_get("@@hair_colors") # => [:brown, :black] Person.new.hair_colors = [:blonde, :red] Person.class_variable_get("@@hair_colors") # => [:blonde, :red]
The attribute name must be a valid method name in Ruby.
class Person cattr_writer :"1_Badname " end # => NameError: invalid attribute name
If you want to opt out the instance writer method, pass :instance_writer => false or :instance_accessor => false.
class Person cattr_writer :hair_colors, :instance_writer => false end Person.new.hair_colors = [:blonde, :red] # => NoMethodError
Also, you can pass a block to set up the attribute with a default value.
class Person cattr_writer :hair_colors do [:brown, :black, :blonde, :red] end end Person.class_variable_get("@@hair_colors") # => [:brown, :black, :blonde, :red]
Register or
log in
to add new notes.
zvoase -
January 27, 2009 - (v2.1.0 - v2.2.1)
1 thank
Description
Similar to Ruby’s built-in attr_writer, only it creates a class attribute writer method (as opposed to an instance attribute writer method).