Samuel
Samuel

Reputation: 2442

Instantiating a class in Ruby and populating instance variable

I have a feeling I'm missing something very simple here. I have a class that is linked to an external service. I want to instantiate it by either calling a create method or a find method. Both methods will populate an instance variable "@node" with a hash, either by creating a node or finding it.

I have

class GenreInfluence

@@neo ||= Neography::Rest.new()
attr_accessor :node

def initialize
end

def self.create
    @node = @@neo.create_node
    self.new
end

def self.find(node_id)
    @node = @@neo.get_node(node_id)
    self.new
end

def get_hash
  @node
end

If I comment out what's going on, I can see it's creating the class and getting the correct hash back however:

theInstance = GenreInfluence.find(20)
theInstance.get_hash

Just returns nil. Why is the hash not being stored in the instance variable!?

Upvotes: 3

Views: 10078

Answers (3)

Steve Wilhelm
Steve Wilhelm

Reputation: 6260

How about

class GenreInfluence

@@neo ||= Neography::Rest.new()
attr_accessor :node

def initialize(node_id = nil)
    if (node_id.nil?) then
        @node = @@neo.create_node
    else
        @node = @@neo.get_node(node_id)
    end
end

def find(node_id)
    @node = @@neo.get_node(node_id)
end

def get_hash
  @node
end

end

and then

theInstance = GenreInfluence.new()
theInstance.get_hash

theInstance1 = GenreInfluence.new(20)
theInstance1.get_hash

theInstance2 = GenreInfluence.new()
theInstance2.get_hash
theInstance2.find(20)
theInstance2.get_hash

Upvotes: 1

jdl
jdl

Reputation: 17790

You are returning self.new from your find method. That's a new instance of GenreInfluence with a fresh set of instance variables.

Upvotes: 4

Michelle Tilley
Michelle Tilley

Reputation: 159095

You can't set instance variables in a non-instance (static, or class) method. Furthermore, both your methods are returning self.new, which effectively returns a new instance of the class with no instance variables set.

How about the following, that creates a new instance of the class in the static class methods, sets the variable on that instance, and then returns it (instead of returning self.new):

class GenreInfluence
  @@neo ||= Neography::Rest.new()
  attr_accessor :node

  def initialize
  end

  def self.create
    influence      = self.new
    influence.node = @@neo.create_node
    influence
  end

  def self.find(node_id)
    influence      = self.new
    influence.node = @@neo.get_node(node_id)
    influence
  end

  def get_hash
    @node
  end
end

Upvotes: 10

Related Questions