Public/private/protected instead of def

First of all, I am curious. Is there any way to do the following but
still retain backward compatibility?

class Module
# unfortunately super doesn’t work
alias :publicize :public
alias :privatize :private
alias :protect :protected

def public(name, &code)
  define_method(name, &code) if code
  publicize(name)
end

def private(name, &code)
  define_method(name, &code) if code
  privatize(name)
end

def protected(name, &code)
  define_method(name, &code) if code
  protect(name)
end

end

Example

class X

public :x do |*a|
  p a
end

private :y do |*a|
  p a
end

protected :z do |*a|
  p a
end

end

Secondly, I guess ‘def’ was just nice because of it’s uniformity
throughout modules and classes, but I have to wonder if the more Java
like to use of public/private/protected might ultimately be a bit more
beneficial (especially if they could be generalized to allow the
definition of others via meta-programming). Classes might look more
like:

class X

public_accessor :a

private_reader :b

protected_writer :c

public x(*a)
  p a
end

private y(*a)
  p a
end

protected z(*a)
  p a
end

end

I should point out why this even crossed my mind. I have a piece of
code like so:

class C < Module
def initialize(&block)
instance_eval(&block)
end
end

Within it the normal public/private/protected do not work.

M = C.new do
private
define_method(:x){ “x” }
end

class X
include M
end

X.new.x #=> “x” (instead of an error)

So it occurred to to make public/private/protected helper methods in
this context, which led me to the larger thought.

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