简体   繁体   中英

How works these methods in controllers, assets in js?

I have this example
And i wanna understand what it is " ||= " in this method? How it works?

First segment

 def current_user
            @current_user ||= User.find(session[:user_id]) if session[:user_id]
          end

also, i dont know what does (function()) mean in Ruby on rails. Its not simple function(), why is it inside brackets?

Second example

(function() {
  this.App || (this.App = {});

  App.cable = ActionCable.createConsumer();

}).call(this);

The ||= is equivalent to

@current_user || @current_user = User.find(session[:user_id]) if session[:user_id]

Meaning, if @current_user is nil or false set @current_user to be the value of User.find(session[:user_id]) in the case there is a session[:user_id]

The second example is not Ruby on Rails, but JavaScript. It's the so called “Immediately Invoked Function Expressions" and it's wrapped with parenthesis so that you can call it with a specific parameter, in your case this . So that the this inside the IIFE has the context of where that IIFF was called.

If you think about other operators, it will be easier to see what this memoize does.

When we do @var += 1 , we are basically saying @var = @var + 1 . That's the same for other operators:

@var -= 1 => @var = @var - 1 @var ||= 1 => @var = @var || 1 @var = @var || 1

That means that, if @var is set, it does not change its value, but if @var is nil, it will set its value with the one you provided. It works like a cache, if there is a value, use it, but if there is not, set the new value and use it.

Try this on the terminal:

[1] pry(main)> var ||= 10
=> 10
[2] pry(main)> var ||= 20
=> 10
[3] pry(main)> var = nil
=> nil
[4] pry(main)> var ||= 20
=> 20

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM