sonic-pi

https://github.com/sonic-pi-net/sonic-pi

C++

Code. Music. Live.

Module#mattr_reader

Defines a class attribute and creates a class and instance reader methods.
The underlying the class variable is set to +nil+, if it is not previously
defined.

  module HairColors
    mattr_reader :hair_colors
  end

  HairColors.hair_colors # => nil
  HairColors.class_variable_set("@@hair_colors", [:brown, :black])
  HairColors.hair_colors # => [:brown, :black]

The attribute name must be a valid method name in Ruby.

  module Foo
    mattr_reader :"1_Badname "
  end
  # => NameError: invalid attribute name

If you want to opt out the creation on the instance reader method, pass
<tt>instance_reader: false</tt> or <tt>instance_accessor: false</tt>.

  module HairColors
    mattr_writer :hair_colors, instance_reader: false
  end

  class Person
    include HairColors
  end

  Person.new.hair_colors # => NoMethodError


Also, you can pass a block to set up the attribute with a default value.

  module HairColors
    cattr_reader :hair_colors do
      [:brown, :black, :blonde, :red]
    end
  end

  class Person
    include HairColors
  end

  Person.hair_colors # => [:brown, :black, :blonde, :red]

Source | Google | Stack overflow

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 branch

git checkout -b -your-name--update-docs-Module-mattr_reader-for-pr


# Commit to git

git 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_reader"


# Open pull request

gem install hub # on a mac you can `brew install hub`

hub fork

git push <your name> -your-name--update-docs-Module-mattr_reader-for-pr

hub pull-request


# Celebrate!