Explanation of method

hey i have a method

def admin_login_required
username, passwd = get_auth_data
self.current_user ||= User.authenticate(username, passwd)
|| :false if username && passwd
logged_in? && authorized? ? true : access_denied
end

this is from an authentication plugin. i cant make sense of it, and
dont understand wot the ‘||=’ symbol does. i cant google for it, cos
google strips the search for the symbol. can someone explain step by
step wot the function is doing ?

On 5 Nov 2007, at 05:57, Chubbs wrote:

this is from an authentication plugin. i cant make sense of it, and
dont understand wot the ‘||=’ symbol does. i cant google for it, cos
google strips the search for the symbol. can someone explain step by
step wot the function is doing ?

This is a ruby question so probably better suited to other places, but
anyway,
for most operators
a op= b is the same as a = a op b
So a ||= b is the same a = a || b
Because of the way ruby evaluates these things, it means set a to b
unless a is already set (in which case it won’t even evaluate b).

Fred

Hi –

On Mon, 5 Nov 2007, Frederick C. wrote:

|| :false if username && passwd
This is a ruby question so probably better suited to other places, but
anyway,
for most operators
a op= b is the same as a = a op b
So a ||= b is the same a = a || b
Because of the way ruby evaluates these things, it means set a to b
unless a is already set (in which case it won’t even evaluate b).

There’s at least one edge-case which reveals that it a ||= b and
a = a || b aren’t quite the same:

irb(main):007:0> h = Hash.new(1)
=> {}
irb(main):008:0> h[:x] ||= 2
=> 1
irb(main):009:0> h
=> {}

Here’s what happens with the plain || version:

irb(main):010:0> h[:y] = h[:y] || 3
=> 1
irb(main):011:0> h
=> {:y=>1}

Matz had something to say about ||= at the Ruby Clinic that I
conducted on Friday at RubyConf – namely, that it’s better to think
of it this way:

x ||= y => x || (x = y)

Translating my example that way produces the right result.

David


Upcoming training by David A. Black/Ruby Power and Light, LLC:

  • Advancing With Rails, Edison, NJ, November 6-9
  • Advancing With Rails, Berlin, Germany, November 19-22
  • Intro to Rails, London, UK, December 3-6 (by Skills Matter)
    See http://www.rubypal.com for details!

On 5 Nov 2007, at 10:36, David A. Black wrote:

Matz had something to say about ||= at the Ruby Clinic that I
conducted on Friday at RubyConf – namely, that it’s better to think
of it this way:

x ||= y => x || (x = y)

You learn something everyday! Thanks for that.

Fred