Kitty1911
Kitty1911

Reputation: 681

access static method from controller instance variable

Supposing I have a model A like:

class A
  def self.base_attributes
    {:state_a => nil}
  end 

  def self.aa(params)
    instance = load
    instance.state_a = {:xx => params[:x]...}
    instance
  end

  def cc(x)
    self.state_a[..] = x
    self.save!
  end
end

and I have a controller B like:

controller B
  def mtd
    @aaa = A.aa(params)
    #operations to get y
    @aaa.cc(y)
  end
end

Is there a way in which I can make the model method cc(x) a static method and call it from the instance variable of the controller (@aaa)?

Upvotes: 0

Views: 1510

Answers (2)

7stud
7stud

Reputation: 48599

Is there a way in which I can make the model method cc(x) a static method and call it from the instance variable of the controller (@aaa)?

A static class method has to be called with the class object as the receiver, and an instance method has to be called with the instance method as the receiver.

Why do you care what type of method it is if you are going to call it with the instance?

Response to comment:

Then the instance that load() returns is not an instance of class A. It's very simple to test that what you want to do works: in one of your actions in your controller write:

@my_a = A.new
@my_a.do_stuff

Then in your model write:

class A

  def do_stuff
    logger.debug "do_stuff was called"
  end
  ...
  ...
end

Then use the proper url, or click the proper link to make that action execute. Then look at the bottom of the file:

log/development.log

...and you will see a line that reads:

"do_stuff was called"

You can also record the type of the object that load() returns by writing:

  def self.aa(params)
    instance = load
    logger.debug instance.class  #<===ADD THIS LINE
    instance.state_a = {:xx => params[:x]...}
    instance
  end

Upvotes: 1

Peter Alfvin
Peter Alfvin

Reputation: 29409

It's not clear what load does, but in any event, if @aaa is an instance of A and cc is a class method of A, then you can invoke cc with the expression @aaa.class.cc.

Upvotes: 0

Related Questions