修改每个块条目以调用块参数上的方法

发布于 2025-01-13 11:30:29 字数 530 浏览 2 评论 0原文

在我的一个视图中,我使用辅助方法渲染了一个表,因此视图(haml)看起来像这样:

= table do
  - action "Add"
  - column :id
  - column :name

在我更改辅助方法并使用 ViewComponent 库之后,我需要按以下方式调用它:

= table do |t|
  - t.action "Add"
  - t.column :id
  - t.column :name

我想知道它是否是可以在辅助方法中将示例 1 中的块转换为示例 1 中的块,因此我不需要重写每个使用表的视图。

辅助方法如下所示:

def table(*args, **kwargs, &block)
  # ...
  render TableComponent.new(*args, **kwargs, &new_block)
end

In one of my views, I rendered a table with a helper method, so the view (haml) looked like this:

= table do
  - action "Add"
  - column :id
  - column :name

After I changed the helper and used the ViewComponent lib instead, I need to call it the following way:

= table do |t|
  - t.action "Add"
  - t.column :id
  - t.column :name

I wondered if it's possible to convert the block in example 1 to the block in example 1 in a helper method, so I don't need to rewrite every view that uses a table.

The helper method would look like:

def table(*args, **kwargs, &block)
  # ...
  render TableComponent.new(*args, **kwargs, &new_block)
end

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

悟红尘 2025-01-20 11:30:29

让我们将您的示例简化为:

class Table
  def initialize
    @rows = []
  end

  def action(name)
    @rows << "Action #{name}"
  end

  def column(name)
    @rows << "Column #{name}"
  end

  def to_s
    "Table:\n======\n#{@rows.join("\n")}"
  end
end

def table(&block)
  t = Table.new
  block.call(t)
  t
end

puts(
  table do |t|
    t.action "Add"
    t.column :id
    t.column :name
  end
)

这给出了:

Table:
======
Action Add
Column id
Column name

现在您想要执行的操作:

  table do
    action "Add"
    column :id
    column :name
  end

因此您希望块的主体与实例处于相同的上下文中(例如,就像在 Table 实例中一样),所以:(

def table(&block)
  t = Table.new
  t.instance_eval(&block)
  t
end

这就是大多数领域特定语言的诞生 :) )

Let's simplify your example to this:

class Table
  def initialize
    @rows = []
  end

  def action(name)
    @rows << "Action #{name}"
  end

  def column(name)
    @rows << "Column #{name}"
  end

  def to_s
    "Table:\n======\n#{@rows.join("\n")}"
  end
end

def table(&block)
  t = Table.new
  block.call(t)
  t
end

puts(
  table do |t|
    t.action "Add"
    t.column :id
    t.column :name
  end
)

That gives:

Table:
======
Action Add
Column id
Column name

Now you want to do:

  table do
    action "Add"
    column :id
    column :name
  end

So you want to have the body of the block be in the same context as the instance (e.g. like being in a Table instance), so:

def table(&block)
  t = Table.new
  t.instance_eval(&block)
  t
end

(that's how most Domain Specific Languages are made :) )

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文