开发者

ruby rescue constant missing?

few months ago I've been using some ruby library ( I can't recall which one exactly, unfortunately )

I've been surprised to see it allowed me to initialize it's instance with something like that:

Lib::SOMETHING(args)

I don't 开发者_JAVA技巧really understand how it could possibly work. I'm pretty much sure it should be something dynamic ( there's no SOMETHING constant ) like constant_missing module method or maybe the ConstantMissing exception gets handled somehow.

Could you please advice?


No magic there in theory, it just looks unfamiliar:

class A
  def self.I_LOOK_LIKE_A_CONST(arg)
    puts arg
  end
end

A::I_LOOK_LIKE_A_CONST("Hi") # => "Hi"

Net::HTTP does something similar with its Proxy class, it allows calls such as Net::HTTP::Proxy(...), it is defined similarly:

def HTTP.Proxy(p_addr, p_port = nil, p_user = nil, p_pass = nil)

The punch line is that for class methods you can interchangeably use :: or . to invoke them.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜