Mattr_accessor inside a class

Rails extends Ruby with mattr_accessor (Module accessor). As Ruby’s
attr_accessor generates getter/setter methods for instances,
mattr_accessor provide getter/setter methods at the module level. In
below example, you see that mattr_accessor declared in the class
context of LookupContext. It’s declared in class, not module. However,
modules are defined in LookupContext, for example, the module
ViewPaths, which makes use of the accessor. So is it safe to say that
if a module accessor is declared in class, then it can only be
available to modules of that class?

class LookupContext
mattr_accessor :fallbacks
module ViewPaths
self.class.fallbacks.each do |resolver|

it looks as if it is onyl available on the class because if you look
it says self.class.fallbacks, yet that wouldnt make sense either
because then what would be the point of its existance if you had to
reach the class for it it, why not just create a class level macro
instead?

John M. wrote in post #1075232:

Rails extends Ruby with mattr_accessor (Module accessor). As Ruby’s
attr_accessor generates getter/setter methods for instances,
mattr_accessor provide getter/setter methods at the module level. In
below example, you see that mattr_accessor declared in the class
context of LookupContext. It’s declared in class, not module.

A class is a module.

However,
modules are defined in LookupContext, for example, the module
ViewPaths, which makes use of the accessor. So is it safe to say that
if a module accessor is declared in class, then it can only be
available to modules of that class?

What is ‘it’?

class LookupContext
def LookupContext.fallbacks
@@fallbacks
end

def LookupContext.fallbacks=(arr)
@@fallbacks = arr
end

module ViewPaths
def ViewPaths.greet
p LookupContext.fallbacks
end
end
end

class Dog
def bark
p LookupContext.fallbacks
end
end

LookupContext.fallbacks = [10, 20, 30]
p LookupContext.fallbacks

LookupContext::ViewPaths.greet
Dog.new.bark

–output:–
[10, 20, 30]
[10, 20, 30]
[10, 20, 30]

In this code:

module ViewPaths
self.class.fallbacks.each do |resolver|

…self is the module LookupContext::ViewPaths, and self.class is
Module, and Module has no method ‘fallbacks’:

class LookupContext
def LookupContext.fallbacks
@@fallbacks
end

def LookupContext.fallbacks=(arr)
@@fallbacks = arr
end

module ViewPaths
puts self
puts
puts self.class
puts
puts self.class.fallbacks
end
end

–output:–
LookupContext::ViewPaths

Module

1.rb:60:in <module:ViewPaths>': undefined methodfallbacks’ for
Module:Class (NoMethodError)
from 1.rb:57:in <class:LookupContext>' from 1.rb:48:in

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs