Are imported Ruby methods always private?

This is best explained with an example:

file1.rb:

def foo
  puts 123
end

file2.rb:

class A
  require 'file1'
end
A.new.foo

will throw an error ": private method 'foo' called".

I can get around this by doing A.new.send("foo"), but is there a way to publish imported methods?

Edit: To clarify, I do not confuse include and require. Also, the reason I can't use normal inclusion (as many have correctly pointed out) is because it is part of the metaprogramming. I need to allow the user to add functionality at runtime; for example, it might say “run-this-app -include file1.rb,” and the application will behave differently based on the code that it wrote in file1.rb. Sorry, should have explained more clearly.

: Jorg, , , , () . - str=(entire file1.rb as string); A.class_exec(str).

+5
3

Ruby . , . , , , Object. Ruby , , , self , self , Object.

, :

# file1.rb

def foo
  puts 123
end

# file1.rb

class Object
  private

  def foo
    puts 123
  end
end

, foo, :

foo

, , ,

self.foo

self - , Object , foo .

[: , , self. , , self.send(:foo), self.foo.]

A.new.foo file2.rb - : Object.new.foo [].foo 42.foo .

: puts require " ", Object (, Kernel, Object).

: require , , require d - , , , , require , .

,

# file2.rb

class A
  require 'file1.rb'
end

- , . , :

# file2.rb

require 'file1.rb'

class A
end

, , file1.rb A.

, , require 'file1' require 'file1.rb'. Ruby , , ( MRI, YARV, Rubinius, MacRuby JRuby), - JVM .jar .class ( JRuby), CIL .dll ( IronRuby) .., require.

: - send, instance_eval, .. A.new.send(:foo) A.new.instance_eval {foo}.

+7

Ruby. mixins :

file1.rb:

module IncludesFoo
  def foo
    puts 123
  end
end

file2.rb:

require 'file1.rb'

class A
  include IncludesFoo
end

A.new.foo
# => 123
+10

load("file1", A)? ( RDoc)

0

All Articles