Ritumoni Sharma
Ritumoni Sharma

Reputation: 71

Calling a class from a function in another class

I am stuck on calling a class inside a function in another class. Let's assume I have a class A and functions self.B and c,

class A
  def self.b
    //does something
  end
  def c
    //does something
  end
end

and another class D:

class D
  before_create :x
  def x
    //have to call the class A and its functions here
  end
end

Please tell me how to acheive this.

Upvotes: 0

Views: 1719

Answers (2)

ReggieB
ReggieB

Reputation: 8212

The A method b is simple, that is a class method and can be invoked directly from that class. So

class D
  def y
    A.b
  end
end

A method c is more interesting as that is an instance method. So you need to create an instance of class A and then invoke its method c. You can do it like this:

class D
  def z
    A.new.c
  end
end

However, you usually call instance methods because the output is determined by parameters assigned to that instance. So rather than calling method c on a new instance of A, you'll usually want to create the new instance, configure it the required way, and then pass it to the class D method. So you need to pass the A instance to the D method. You'd usually do that like this:

class D
  def z(a)
    a.c
  end
end

a = A.new
d = D.new

d.z(a) 

Upvotes: 2

Yury Lebedev
Yury Lebedev

Reputation: 4005

You an call the class methods directly on a class, and to call instance methods, you need to create an instance of the class:

Class D
  before_create :x

  def x
    # for a class method
    A.b

    # for an instance method
    a = A.new
    a.c 
  end
end

Upvotes: 5

Related Questions