Global objects?


#1

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?


#2

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


#3

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


#4

pat,

that’s awesome (and definatley understandable) I’ll give that a try
later today.