0

I want to use the object created in main script globally.

for ex I have different module in different file and class in different ruby file

FileNameModA.rb

module A
  # ........
  # some code here
  # ........
end

FileNameModB.rb

module B
  # ........
  # some code here
  # ........
  objReport.addReport() # getting an error "ruby uninitialized local variable or object: Main"
end

FileNameClass_Report.rb

class Report
  def addreport()
  end
end

MainScript.rb

require "FileNameModA"
require "FileNameModB"
require "FileNameClass_Report"

include ModuleA
include ModuleB

objReport = Report.New

objReport.addReport() # Works fine here

Could you please let me know how to create and use object in different file/module of Ruby?

2
  • 1
    Which version of Ruby are you using? Require statements are handled a little different in 1.9 and 1.8, where you'll want to use require_relative 'filename' in 1.9+. Commented Jul 9, 2012 at 17:41
  • Why would you expect objReport.addReport() to work in FileNameModB.rb? Commented Jul 12, 2012 at 1:21

1 Answer 1

2

when you require "FileNameModB" it executes the definition of module B and that definition calls objReport.addReport which does not exist in that context

i'm not sure what are you trying to achieve by calling addReport during module definition but you could swap some lines and make it work like this:

require "FileNameClass_Report"
$objReport = Report.New

require "FileNameModA"
require "FileNameModB" # update your file to call $objReport.addReport

include ModuleA
include ModuleB

whole thing looks like a mess though, try to rethink your classes/modules to avoid including them into global object

Sign up to request clarification or add additional context in comments.

2 Comments

I am automating an application using Ruby(Watir). For this i have Main scirpt, Function library, report.rb and object repository in different file/folder. Report.rb has a Class but not module and other are defined in modules. In the main script i have created an object of the report class which is working fine. but i want to use the the function defined in report class in the function library.
what i'm saying is that i don't understand why you need to include ModuleA into global object - why not just call functions of ModuleA explicitly?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.