轨道上的红宝石 - 为什么在使用路由帮助程序方法时必须使用括号



知道这在 Ruby 中是可能的:

method_name param, other_method other_param

在另一种编程语言中,这将等效于:

method_name(param, other_method(other_param))

为什么无法使用自动生成的路由帮助程序来执行此操作,这些方法与其他方法一样?

例如:

<%= link_to ticket.subject, ticket_path(ticket.id) %>

是有效的 — 例如,它返回 <a href="/tickets/1">Lorem ipsum.</a> ,但是:

<%= link_to ticket.subject, ticket_path ticket.id %>

不是 — 它返回一个unexpected tIDENTIFIER错误。

method_name param, other_method other_param

Ruby 中是不可能的,所以路由帮助程序也是不可能的,因为它是不明确的。

在Matz的Ruby编程语言中甚至有一节关于这一点。

例:

irb(main):001:0> def link_to(a, b)
irb(main):002:1> puts a, b
irb(main):003:1> end
:link_to
irb(main):004:0> def foo(a)
irb(main):005:1> puts 'foo'
irb(main):006:1> end
:foo
irb(main):007:0> link_to 'hello', foo 'abc'
SyntaxError: (irb):7: syntax error, unexpected tSTRING_BEG, expecting keyword_do or '{' or '('
link_to 'hello', foo 'abc'
                      ^
    from /usr/local/var/rbenv/versions/2.2.2/bin/irb:11:in `<main>'
irb(main):008:0> link_to 'hello', foo('abc')
foo
hello
nil

最新更新