When I put a method that refers to a pulled in package inside another method it leaves scope and fails.
What is the proper way to do this. I tried playing with the 'self' but am new and that did not work out.
Desired solution. Does not work. Returns error.
undefined method `accounts' for nil:NilClass (NoMethodError)
require 'package that has 'accounts''
class Name
@sandbox = #working API connection
def get_account
@sandbox.accounts do |resp| #This is where error is
resp.each do |account|
if account.name == "John"
name = account.name
end
end
end
end
end
new = Name.new
p new.get_account
This works but does not create a reusable method.
require 'package that has 'accounts''
class Name
@sandbox = #working API connection
@sandbox.accounts do |resp|
resp.each do |account|
if account.name == "John"
p account.name
end
end
end
end
new = Name.new
The mistake in the code is that @sandbox is an attribute of the class. The value would be initialized when an object of the class is created. Writing the initialization in the class will have no effect. @Maxim has explained this in his answer.
For the second code, when the interpreter runs through the code, it would execute it once. But that code cannot run more than once.
The code should be,
require 'package that has 'accounts''
class Name
def initialize
@sandbox = #working API connection
end
def get_account
@sandbox.accounts do |resp| #This is where error is
resp.each do |account|
if account.name == "John"
name = account.name
end
end
end
end
end
new = Name.new
p new.get_account
To understand this, you need to understand the concept of singleton classes in Ruby.
The class Name is an object itself, and @sandbox
is an instance variable of that object.
If you write def self.get_account
you could use @sandox
there, but then this method is not available for instances of Name, e.g. you should call Name.get_account
and not Name.new.get_account
. Actually, this adds a method to the singleton class of Name, and that's why you can access @sandbox there.
To create an instance variable that could be used in the instances of Name
, you should do so in the initialize
method of Name
.