开发者

One class instance throw all controller

i i have different class and controller. and i need that one instance of model will be availab开发者_如何学Pythonle 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...


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


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜