views:

32

answers:

2

Hello i i have different class and controller. and i need that one instance of model will be available in controller/ now i'm doing something like this:

def method1
    inst = @MyClass.new(params)
    inst.action
    ....
def method2
    inst = @MyClass.new(params)
    inst.action
    ....

but i want something like this

def method1    
     @inst.action
    ....
def method2
     @inst.action

or self.inst i't doesn't matter

how i can do it?

def self.inst
    MyClass.new(params)
end

doesn't work...

A: 

It looks like you're confused about when to use instance variables.

In the first part of your code, you're saying

inst = @MyClass.new(params)
inst.action

This is grabbing the object stored in the instance variable @MyClass, calling new on it, and storing the result of that in the local variable inst.

But when you want to do @inst.action in the second set of code, you're relying on @inst being returned from a method self.inst, which is a method, not an instance variable. Moreover, the self.inst method is no longer accessing the @MyClass instance variable -- it's accessing a constant named MyClass.

I think what you want, from what you've written, is:

def inst
  @MyClass.new(params) # access instance variable
end

def method1
  inst.action  # call a method that access the instance variable, then call `action` on that
  # or `self.inst.action` would be equivalent
  # ...
end
Mark Rushakoff
but as i can think @MyClass.new(params) will be executing every time then i do 2inst.action" ?i want only 1 .new(params) and only 1 variable per controller
Falcon
+1  A: 

You can use a before_filter callback.

Heres how you use it


 class YourController < ApplicationController

   before_filter :find_resource 

   def action1
      @some_instance.magic
   end

   def action2
     @some_instance.magic
   end

  private
   def find_resource
      @some_instance = YourModel.find
   end

 end

You can also specify the actions that callback is run on with :only or :except options

HTH

Rishav Rastogi
thanks. i thought about this. but in this situation YourModel.find will be executed more that one time.. I search method to execute 1 time and use always.
Falcon
the callback is called only once per request ( an action is also called once per request )
Rishav Rastogi