Ruby 在 运行 时加载方法或编译?

Ruby loads the methods at run time or compile?

我在一个平台上工作,他们要求我集成 Pundit gem。创建策略时,我意识到许多方法具有相同的访问控制策略。 示例:

Action1: Only accessible by the administrator or owner of the resource
Action2: Only accessible by the administrator or owner of the resource
Action3: Only accessible by the administrator or owner of the resource
.
.
.

然后我想到了用下面的方式创建动态方法

[: Action1 ?,: Action2? ,: Action3?].each do |meth|
     define_method(meth){@current_user.admin? or @current_user.owner_resource?}
end

但我有一个问题: Ruby on Rails 是在 运行 时还是在编译时执行方法? 创建动态方法是最优还是以静态方式分别创建 3 个方法更好?

谢谢!!!

Does Ruby on Rails execute the methods at run time or at compile time?

运行时。

方法将在第一次解释时被 解析 ,但实际代码直到 运行.

才会被评估

方法定义可能包含完全无意义的内容(例如未定义的变量)——但除非它包含语法错误,否则不会在实际调用代码之前暴露。

...而这纯粹是 "ruby" 的事情;无论您是否使用 rails 框架,它都会发生。

Is it optimal to create dynamic methods or is it better to create 3 methods separately in a static way?

这取决于你所说的 "optimal" 的意思。

在性能方面,它比静态方法稍微快一些。但是除非你正在构建一个核心库,否则差异可以忽略不计 - 所以我不会担心这一点。

但是,还有其他充分的理由尽可能静态地定义方法。即:代码不那么混乱,更容易导航到方法定义(例如,当使用 IDE 时),并且当元编程较少时更容易更改方法定义。

就个人而言,我可能倾向于将这些方法定义为:

def action1?
  user.admin? || user == record.owner
end

def action2?
  action1?
end

def action3?
  action1?
end

(但不知道 action 到底是什么,或者它们如何适应更广泛的应用程序上下文,很难给出具体的建议。)

或者,如果您愿意,也可以使用 alias