code0079
code0079

Reputation: 177

loop inside Model.new in rails

I know it's a very short question. I understand "{ }" represents a loop. and the new operator creates a new active record object.

What does this line do in rails? from where does lead come?

Proc.new{|lead| lead.lead_details.name}

Upvotes: 0

Views: 94

Answers (1)

Marek Lipka
Marek Lipka

Reputation: 51171

It creates new Proc object. lead doest't come from anywhere in this example since this Proc doesn't get called. But you can call that, passing it as a block, for example.

leads = Lead.includes(:lead_details) # I assume it's an AR model, obviously
p = Proc.new { |lead| lead.lead_details.name }
names = leads.map(&p)

This way, lead comes from map method and represent single element of leads array-like object, it's equivalent to this:

leads.map { |lead| lead.lead_details.name }

You can also call this procedure 'by hand', passing argument explicitly, like this:

p.call(leads.first)
# => Whatever is leads.first.lead_details.name

You can even write your own method using it as block, for example:

def first_do(collection)
  yield(collection.first)
end
first_do(leads, &p)
# => Whatever is leads.first.lead_details.name

Upvotes: 2

Related Questions