Forum: Ruby Methods that return a hash or an exception?

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
Sean H. (Guest)
on 2006-04-06 23:07
(Received via mailing list)
Hi everyone,

I'm not quite sure how to handle this type of thing.  I have a method
that searches for a user in our LDAP by way of a Person model's
username attribute:

@ldap_person = @person.get_ldap_user

This method, noce done with the LDAP wrangling, returns the user entry
(an LDAP::Entry object) as a hash:

return conn.search2(UnifiedLDAP::PEOPLE_DN, LDAP::LDAP_SCOPE_SUBTREE,
filter, self.ldap_attributes)[0].to_hash

This works, and, of course, there SHOULD be an LDAP entry
corresponding to that Person, but if there isn't or LDAP is
unreachable, I want to report that.  Am I doing the wrong thing in
returning a hash?  Where should I be catching exceptions?  How should
I be then be dealing with them?

This is part of a Rails app, but I don't think that part is important,
so I'm sticking to this list.  When I pass @ldap_person to the view,
though, and @ldap_person is an exception, obviously, this doesn't

Thank you!

Jamey C. (Guest)
on 2006-04-06 23:40
(Received via mailing list)
Sean H. wrote:

>so I'm sticking to this list.  When I pass @ldap_person to the view,
>though, and @ldap_person is an exception, obviously, this doesn't
One idea off the top of my head would be to catch the exception in
#get_ldap_user and have the rescue clause return nil.  Then, when you
pass @ldap_person to your view, you could have something like:  <%
@ldap_person || "" %> in your rhtml file, so that if @ldap_person is
nil, it just prints an empty string.


Sean H. (Guest)
on 2006-04-07 00:17
(Received via mailing list)
Ok, yeah, that worked.  Thanks!  There's a little more code in the
view and controller than I'd like, but I'll be able to refactor that
as I get better at Ruby.  :)

What I have now (the Person model just returns nil if there was an

if !(@ldap_person = @person.get_ldap_user)
  flash[:error] = "User does not exist in LDAP or LDAP unreachable"


<% if flash[:error] %>
	<%= flash[:error] %>
	<% flash[:error] = nil %>
<% else %>
....everything else for a successful user find...
<% end %>

So, yeah, not the best, but it definitely gets me to a place where I
can show this to the client and work on fleshing out error handling a
bit more.

Thank you!

This topic is locked and can not be replied to.