How to DRY up this code

Hello,

I have a piece of controller code that needs to be dried up. The part
between the big comment blocks (####) is the only (!) part of the code
that
needs to change for various methods.

I couldn’t figure it out because if I would wrap this code in a Proc or
lambda, the render :nothing => true statement would become void because
it
doesn’t run in the context of the controller anymore.


def authenticate
if request.method.eql?(:post)
request = convert_xml_to_object(:request, params[:xml])
# Prepare default response
response = default_response
# Get the account
account = Account.find_by_email request.username
# Check for API credentials
if check_api_credentials(account, request, response)
# _ 12221 baz bar
good = false
# If we find something good, let’s actually do something!

########################################################################
good = account.authenticate :password => request.password,
:source
=> request.source
# End of block

########################################################################
# This sound a bit … Polish :]
if good
set_response_to_100(response)
end
end
# _
respond_to do |format|
format.xml { render :xml => response.to_xml }
end
else
render :nothing => true
end
end

i dont really see you repeating yourself. the reusable parts of your
code already seem to be moved into methods. i think you are asking
people to refactor your code…

Commander J. wrote in post #958574:

Hello,

I have a piece of controller code that needs to be dried up. The part
between the big comment blocks (####) is the only (!) part of the code
that
needs to change for various methods.

That method is far too long to be in the controller. Most of this
should be abstracted into models.

Better yet, just rip it all out and install Authlogic or Devise. There
is absolutely no reason to write your own authentication code in Rails
when excellent plugins already exist.

Best,

Marnen Laibow-Koser
http://www.marnen.org
[email protected]

Thanks for your reply (and sorry for this late message, didn’t check)

Creating authentication from scratch was a nice exercise, but next time
indeed I’ll just use an auth mechanism.


http://rubyonrailsdeveloper.nl