crystal-lang / crystal

The Crystal Programming Language
https://crystal-lang.org
Apache License 2.0
19.42k stars 1.62k forks source link

How to with-self-yield in initialize? #2026

Closed stugol closed 8 years ago

stugol commented 8 years ago

I don't seem to be able to with self yield in an initialize or new function...?

See https://play.crystal-lang.org/#/r/q4p and https://play.crystal-lang.org/#/r/q4q

JacobUb commented 8 years ago

I don't know about the first one. The second, though: https://play.crystal-lang.org/#/r/q50

bcardiff commented 8 years ago

It could be added, but it will force the type inference to quit some calculations because it will be exposing an object not "completely initialized"

https://play.crystal-lang.org/#/r/q4y

@Exilor workaround is better than the one I was going to post :+1:

stugol commented 8 years ago

@Exilor: Awesome, thank you! Although I'm not sure I understand how it works. Why doesn't the call to new cause an infinite recursion?

JacobUb commented 8 years ago

Because classes have a default new that doesn't yield, and the one I added does. Methods that yield are different from methods that have the same name, the same arguments but don't yield.

stugol commented 8 years ago

@Exilor: Oh, of course!

vladfaust commented 6 years ago

Bumping up. Is that somehow achievable?

class Router
  def initialize(&block)
    with self yield
  end

  def get(path)
  end
end

Router.new do
  get "/"
end

# undefined method 'get'

I currently have to write

Router.new do |r|
  r.get "/"
end

which is kinda overhead.

asterite commented 6 years ago
class Router
  def self.new
    with Router.new yield
  end

  def initialize
  end

  def get(path)
  end
end

Router.new do
  get "/"
end