Noob question... confused


#1

If I have several controller actions which have this same line of code
(or
more), how can I DRY up the line without running into complaints about
redirecting or rendering only once? If I put the line in another method
in
my controller, won’t it think I’m redirecting?

I want to dry up lines like this: @listing = Listing.find(params[:id])

def customerview
@listing = Listing.find(params[:id])
render :action => ‘edit’
end

def view
@listing = Listing.find(params[:id])
render :action => ‘edit’
end

def edit
@listing = Listing.find(params[:id])
render :action => ‘edit’
end

Thanks,

Eric


#2

You can add non-routable methods into controllers by making the method
private:

def customerview
find_listing

… rest of code

end

def view
find_listing

… rest of code

end

private
def edit_listing
@listing = Listing.find(params[:id])
render :action => ‘edit’
end

Steve


#3

This isn’t quite right actually. Should be:

def customerview

… any other code

find_listing
end

def view

… any other code

find_listing
end

private
def edit_listing
@listing = Listing.find(params[:id])
render :action => ‘edit’
end

That’s if you’re rendering the output in the edit_listing method.

Steve


#4

Eric B. wrote:

If I have several controller actions which have this same line of code
(or more), how can I DRY up the line without running into complaints
about redirecting or rendering only once? If I put the line in another
method in my controller, won’t it think I’m redirecting?

I want to dry up lines like this: @listing = Listing.find(params[:id])

You could use a before_filter:

class MyController < ApplicationController
before_filter :find_listing

def customerview
render :action => ‘edit’
end

def view
render :action => ‘edit’
end

def edit
end

private
def find_listing
@listing = Listing.find(params[:id])
end
end


Philip R.
http://tzinfo.rubyforge.org/ – DST-aware timezone library for Ruby