Forum: Ruby on Rails global objects?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Justin J. (Guest)
on 2006-01-26 15:09
Forgive the term global if that's not applicable in rails (i come from a
php background)

I have a browse controller with a couple of different methods

def method1
@properties = Property.find_all
#other stuff for that method
end

def method2
@properties = Property.find_all
#other stuff for that method
end

def method3
@properties = Property.find_all
#other stuff for that method
end

I know RoR is all about not repeating yourself if you don't have to. Is
there a way to say @properties = Property.find_all 1 time and have it be
available to all methods in that particular controller?
Pat M. (Guest)
on 2006-01-26 15:19
(Received via mailing list)
Hey Justin,

You can use before_filter to do what you want.

class FooControlller < ApplicationController
  before_filter do
    @properties = Property.find_all
  end

  def foo
    ...
  end
end
Pat M. (Guest)
on 2006-01-26 15:25
(Received via mailing list)
On second thought there are some points on which I can elaborate..you
can pass in a block as I showed in my first response, and that also
allows you to pass in a method.  So you can do something like

class FooControlller < ApplicationController
  before_filter :my_filter

  def my_filter
    @properties = Property.find_all
    # Do whatever other stuff you want to do for each action
  end
end


You can also have more control over which actions get filtered, using
:only or :except

class FooControlller < ApplicationController
  before_filter :my_filter, :except => :baz

  def foo() end # This gets filtered
  def bar() end # This gets filtered
  def baz() end # NOT filtered

  def my_filter
    @properties = Property.find_all
    # Do whatever other stuff you want to do for each action
  end
end

class FooControlller < ApplicationController
  before_filter :my_filter, :only => :baz

  def foo() end # NOT filtered
  def bar() end # NOT filtered
  def baz() end # This gets filtered

  def my_filter
    @properties = Property.find_all
    # Do whatever other stuff you want to do for each action
  end
end


Of course this is ruby, so it all makes sense anyway.  Just a couple
neat little features that may come in handy.

Pat
Justin J. (Guest)
on 2006-01-26 15:44
pat,

that's awesome (and definatley understandable) I'll give that a try
later today.
This topic is locked and can not be replied to.