Ruby - File-Private Methods

In ruby, is there a way to define a method that each class sees in a file (or in a module), but not files that require a file?

Associated, but not quite the same: is it possible to override a method (for example, a method from a standard library class) so that this override is visible only in the current file? All other files should view the original definition.

+3
source share
2 answers

No and no.

The only appearances in Ruby are public, protected, and private. There is no concept of file-level visibility. Perhaps you can "trick" and do something like this:

# In some file foobar.rb

class Foo
  def to_bar
    Bar.new.file_private
  end
end

class Bar
  def file_private
    raise unless caller[0].split(':')[0] == __FILE__
  end
end
# In IRB or some other file

Foo.new.to_bar  #=> nil
Bar.new.file_private  #=> RuntimeError

. . , .

, . . , public/protected/private. send , . - , , . , :P.

, , . - , , , , , , , .

+8
  • Object (, ). Object, , Foo .

    class Object
      @@file_only_methods = []
    
      def file_only(method_name)
        method_name = method_name.to_sym
        new_method_name = "file_only_#{method_name}".to_sym
        self.send(:alias_method, new_method_name, method_name)
        self.send(:undef_method, method_name)
        self.send(:private, new_method_name)
        @@file_only_methods << method_name
      end
    
    
      def method_missing(method_name, *arg, &block)
        if @@file_only_methods.include? method_name
          if __FILE__ == $0
            self.send("file_only_#{method_name}".to_sym,*arg,&block)
          else
            raise "Method #{method_name} is called outside the definition file."
          end
        else
          raise "Method #{method_name} does not exist."
        end
      end
    end
    
    class Foo
      def bar
        puts 'bar method'
      end
      file_only :bar
    end
    
    Foo.new.bar
    #output:bar method
    Foo.new.x
    #output:no method
    

    2.rb,

    require_relative 'file1'
    Foo.new.bar
    #output: Method bar is called outside the definition file.
    
0

All Articles