Ruby方法作为一个块

时间:2014-07-06 18:18:58

标签: ruby-on-rails ruby

在第389 of Railscasts集中,他创建了一个名为scope_schema的方法,该方法既是在整个剧集中使用的方法,也是作为do

的块传递的方法。

任何方法都可以这样做吗? (*paths)代表什么?我怎样才能创建一个可以成块的方法?我查看了link_to源代码,最后注意到了&block,可以发送给你的发送

<%= link_to ....%>

<%= link_to ... do %>

<%end%>

或者我不正确?

剧集代码:

after_create :create_schema

def create_schema
  connection.execute("create schema tenant#{id}")
  scope_schema do
    load Rails.root.join("db/schema.rb")
    connection.execute("drop table #{self.class.table_name}")
  end
end

def scope_schema(*paths)
  original_search_path = connection.schema_search_path
  connection.schema_search_path = ["tenant#{id}", *paths].join(",")
  yield
ensure
  connection.schema_search_path = original_search_path
end

2 个答案:

答案 0 :(得分:1)

如果您定义了块,则可以使用块调用任何方法。 link_to代码就是一个很好的例子。

对于*paths,这是splat operator,这基本上意味着可以为方法提供任意数量的参数,并将作为相同的参数读取 - 在本例中为paths - 作为阵列。

答案 1 :(得分:1)

可以这样做吗?

是的,只需在方法的参数列表中创建一个块:

def method(arg1, &block)
  # do something with arg1
  # call the block with or without arguments if a block is given:
  block.call() if block_given?
end

def method(arg1)
  # do somehting
  yield
end

Yield可以接收参数。

*(路径)代表什么?

&#39; *&#39;是splat运算符,让您可以根据需要访问多个参数。 (与python相同)

我怎样才能创建一个可以作为块的方法?

方法可以接收块,或者在块中调用,但不能是块。 您可以创建一种方法&#39;然而,在一个过程中。

a = ->(){ puts 'lalala' }

a.call