Hi,
is there a way to call a protected method of a class from a static
method of
the same class? Or to acces an instance variable of a class from a
static
method of the same class?
Now I’m facing a problem. I use some static methods as “factory
methods”, to
create “prefilled” class instances. These methods can’t access the
protected
methods of the same class. Is this behavior intentional? Is there clean
solution to this problem? If not, how can I work around this problem?
This is
a public class, so I don’t want to add other params to initialize.
I get this error
irb(main):032:0> Info.fromBytes("\010\008")
NoMethodError: protected method length=' called for #<Info:0x300c3b70 @length=nil, @typeID=8> from (irb):23:in
fromBytes’
with this class
class Info
def initialize(typeID)
@typeID = typeID
@length = nil
end
attr_reader :typeID
def length
if @length.nil?
@length = veryLongMathCalcs()
end
return @length
end
def Info.fromBytes(bytes)
typeID = bytes[0, 1].unpack("c")[0]
length = bytes[1, 1].unpack("c")[0]
info = Info.new(typeID)
info.length = length ## <<< this is the error!
return info
end
protected
attr_writer :length
end