Why is this lambda coverage area accompanied by a block?

Here is the method described in the Rails API :

scope(name, body, &block)    

This is an example of using this method, also described in the Rails API:

class Shirt < ActiveRecord::Base
  scope :red, -> { where(color: 'red') } do
    def dom_id
      'red_shirts'
    end
  end
end

Question about the following code:

do
  def dom_id
    'red_shirts'
  end
end

What does it mean? I can't find any Ruby syntax about a block that could follow a lambda. Did I miss something? Thanks for any help.

+4
source share
3 answers

In your example, lambda is the second regular argument scope, and block is a block argument scope(not related to lambda syntax).

, ActiveRecord "" , , . , , :

Shirt.red.dom_id

has_many . , ; , .

+2

dom_id id - , Shirt.red.dom_id, Shirt.dom_id. ,

+1

, .

def testLambdaParams(name,body)
  puts name
  body.call
  yield "testLambdaParams_yield" if block_given?
end

second_proc = -> do
  puts "second_proc"
  yield 'second_proc' if block_given?
end


testLambdaParams "first_params",second_proc do |x| 
  puts "block exec for testLambdaParams " + x
end

:

first_params
second_proc
block exec for testLambdaParams testLambdaParams_yield

testLambdaParams, .

+1

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


All Articles