Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!?

like image 594
Samuel Avatar asked Dec 18 '25 19:12

Samuel


2 Answers

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
like image 191
Michelle Tilley Avatar answered Dec 21 '25 09:12

Michelle Tilley


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

like image 41
jdl Avatar answered Dec 21 '25 11:12

jdl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!