sonic-pi
https://github.com/sonic-pi-net/sonic-pi
C++
Code. Music. Live.
Module#mattr_accessor
Defines both class and instance accessors for class attributes.
module HairColors
mattr_accessor :hair_colors
end
class Person
include HairColors
end
Person.hair_colors = [:brown, :black, :blonde, :red]
Person.hair_colors # => [:brown, :black, :blonde, :red]
Person.new.hair_colors # => [:brown, :black, :blonde, :red]
If a subclass changes the value then that would also change the value for
parent class. Similarly if parent class changes the value then that would
change the value of subclasses too.
class Male < Person
end
Male.hair_colors << :blue
Person.hair_colors # => [:brown, :black, :blonde, :red, :blue]
To opt out of the instance writer method, pass <tt>instance_writer: false</tt>.
To opt out of the instance reader method, pass <tt>instance_reader: false</tt>.
module HairColors
mattr_accessor :hair_colors, instance_writer: false, instance_reader: false
end
class Person
include HairColors
end
Person.new.hair_colors = [:brown] # => NoMethodError
Person.new.hair_colors # => NoMethodError
Or pass <tt>instance_accessor: false</tt>, to opt out both instance methods.
module HairColors
mattr_accessor :hair_colors, instance_accessor: false
end
class Person
include HairColors
end
Person.new.hair_colors = [:brown] # => NoMethodError
Person.new.hair_colors # => NoMethodError
Also you can pass a block to set up the attribute with a default value.
module HairColors
mattr_accessor :hair_colors do
[:brown, :black, :blonde, :red]
end
end
class Person
include HairColors
end
Person.class_variable_get("@@hair_colors") #=> [:brown, :black, :blonde, :red]Edit
git clone [email protected]:sonic-pi-net/sonic-pi.git
cd sonic-pi
open app/server/ruby/vendor/activesupport-7.0.6/lib/active_support/core_ext/module/attribute_accessors.rb
Contribute
# Make a new branchgit checkout -b -your-name--update-docs-Module-mattr_accessor-for-pr
# Commit to gitgit add app/server/ruby/vendor/activesupport-7.0.6/lib/active_support/core_ext/module/attribute_accessors.rbgit commit -m "better docs for Module#mattr_accessor"
# Open pull requestgem install hub # on a mac you can `brew install hub`
hub fork
git push <your name> -your-name--update-docs-Module-mattr_accessor-for-pr
hub pull-request
# Celebrate!