Are `return` and` break` useless inside a Ruby block when used as a callback?

In Rails, blocks can be used as callbacks , for example:

class User < ActiveRecord::Base
  validates_presence_of :login, :email

  before_create {|user| user.name = user.login.capitalize
    if user.name.blank?}
end

When such a block is used, is it used for breakand return? I ask because usually in a block it breakwill exit the loop and returnreturn from the environment method. But in the context of the callback, I cannot understand what this means.

The Ruby programming language suggests that it returncan cause LocalJumpError, but I could not reproduce it in the Rails Callback.


Edit : with the following code, I would expect LocalJumpError, but everything returndoes stop the rest of the execution of the callback.

class User < ActiveRecord::Base
  validates_presence_of :login, :email

  before_create do |user|
    return
    user.name = user.login.capitalize
end
+3
2

...

before_create Rails 3, , , . ActiveRecord Rails.

:

class User < ActiveRecord::Base
  validates_presence_of :login, :email

  before_create do
    self.name = login.capitalize if name.blank?
  end
end

- , , ( ).

continue "" .

:

  • continue, , .
  • break, , , .

:

value = [1,2,3,4].each do |i|
  continue if i == 2
  puts i
end

value [1,2,3,4], each, :

1
3
4

:

value = [1,2,3,4].each do |i|
  break if i == 2
  puts i
end

value nil, break each. , break n, value , n. :

1

, continue break , , C .

+10

return Ruby , Proc.new lambda.

: , Proc.new?

, Proc.new.

return , (, , ):

class Foo
  return "bar"
end
+3

Source: https://habr.com/ru/post/1785656/


All Articles