apotonick / gemgem-trbrb

The Trailblazer book's example app.
http://trailblazer.to#book
137 stars 60 forks source link

What does this bit of Ruby wizardry do? #6

Closed HuckyDucky closed 9 years ago

HuckyDucky commented 9 years ago

This is in regards to an example in the book for pre-populating a nested form:

property :user, prepopulate: ->(*) { User.new } do
  property :email
end

I can not figure out, for the life of me, what this is:

->(*) { ... }

What does that stuff do? Why would you not be able to just pass User.new to the prepopulate message?

Titinux commented 9 years ago

It's an anonymous lambda written with the new (ruby 1.9) syntax. It's equivalent to

lambda {|*| User.new }

and no passing User.new is not equivalent. The lambda is evaluated each time the form is pre-populated and if you pass User.new the same instance of User would be used every time.

HuckyDucky commented 9 years ago

Thanks! And the asterisk, is that just a placeholder? Could that have just as easily been x or dummy?

apotonick commented 9 years ago

The askterisk is a "catch all" argument, basically saying "I don't fuckin' care about the arguments passed to me!".

This works for old blocks.

lambda {|*| User.new }

For new 1.9 syntax blocks (still getting used to that).

->(*) { .. }

And, also for methods!

def render(*)
  # no access to incoming arguments here.
end
HuckyDucky commented 9 years ago

You guys are OK, I don't care what anybody says. Thanks!

apotonick commented 9 years ago

Hahaha