0

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

0

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

because I get an error if I call it as @aaa.cc(y) from the controller
See my response at the bottom of my post.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.