ruby - How to get file name with a inherit class? -


I want to get the filename of the Ruby class, which has the heir function. Something like this:

  # a.rb class A def get_file () __FILE__ end-end # BRBI class B & lt; An end # c.rb myobj = B.new () is called myobj.get_file ()  

BRB Expecting, but I have a.rb.

I have many classes like B, so I do not want to add function to each class inherited in A. I would like to add a general method in A class to get good grades. Can anyone help me?

Erik

This is my directory:

 < Code> -Home | -Kirti | -Workpiece | -Rube -Arab | -Brr | - CRB  

file contents below:

a.rb

  square A def Get_file () [__FILE __, $ 0] end of end  

bb.bb

  required_related 'a.rb' class B & lt; One end  

c.rb

  required_related 'BRB' Myobj = B.new () says myobj.get_file ()  

I am now running the code:

  (arup ~> Ruby) $ Ruby c.rb / home / kirti / workspace / ruby ​​ 

The name of the file is currently being executed, including the path relative to the directory where the application was initiated. (Or current directory, if it has been changed). The current file for the running application is in some cases different from the startup file , which is available in the global variable $ 0 .

From the doctor, it is clear __ file __ is an existing file location, which is different from the start-up file $ 0 . Therefore c.rb is your start-up file, but the current file is /home/kirti/workspace/Ruby/a.rb .

Actually, the value of the magic variable __ file __ is a relative path that is created and stored ( but never updated < / Strong>) when your file is loaded. Now in your case you have placed it in the a.rb file, so it is assumed /home/kirti/workspace/ruby/a.rb .

Class B & lt; a; End , that means you add A , in the series of ancestors of the class, B . This does not mean that the methods of A will be added to B . get_file method is still in CAS A . Your object will search for myobj , the first class B inside the method get_file , if not found in class and module), in the series of ancestors Now in the form of class a inside get_file , and in the a file a.rb , the value is therefore The __ file __ should be set to /home/kirti/workspace/ruby/a.rb , when a.rb < / Strong> was loaded for the first time now need_relative 'a.rb' is available in the b.rb file in the class a . Less addressed is, but __ File value will not be updated.

Hope that helps!


Comments