获取所有公共方法和属性 getter 并将它们传递给liquid_methods
如果我们想让方法可以从 Liquid 模板访问,我们需要在模型中将它们声明为 liquid_methods
,如下所示:
class User < ActiveRecord::Base
liquid_methods :name, :adress, :any_method_we_want
...
问题是我们的模型定义了很多东西(属性和公共方法),并且它这将是一个相当大的管理目标,当我们添加新方法时,不要忘记将它们声明为 Liquid_methods,更不用说我们模型顶部的一个非常丑陋的列表了。所以问题是,我想声明所有属性 getter 和公共方法都应该“液化”,是否有比总是手动声明它们以便像示例中那样可访问液体更奇特的方法?你会怎么做?
为了在伪代码中得到这样的结论(可能不起作用):
class User < ActiveRecord::Base
methods = self.public_methods + self.attribute_names
liquid_methods methods
...
If we want to make methods accessible from liquid templates we need to declare them as liquid_methods
in our model, like this:
class User < ActiveRecord::Base
liquid_methods :name, :adress, :any_method_we_want
...
The thing is our model has a lot of stuff (attributes and public methods) defined and it'd be quite a goal to manage and not to forget declare them as liquid_methods when we add new ones, not to mention a really ugly list on the top of our model. So the question is, I'd like to declare that all attribute getters and public methods should be "liquidized", is there a more fancy way than always declaring them manually for the liquid to be accessible like in the example? How would you do that?
To get the point something like this in pseudo code (probably not working):
class User < ActiveRecord::Base
methods = self.public_methods + self.attribute_names
liquid_methods methods
...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我使用 Liquid 并遇到同样的问题。以下是我对您提出的解决方案的建议:
Liquid 的全部目的是不要将您的应用程序的数据或方法过度暴露给编写 Liquid 模板的随机人员。
(如果您只有可信的人编写模板,那么不要使用 Liquid。而是使用 erb、haml、dryml 或其他选择。
如果您有两组人(可信和不可信),那么让您可信的人使用一组类型的模板并将不受信任的人发送给 Liquid。)
如果您默认公开您的方法,那么测试您没有公开太多的方法就会困难得多。
当然,您最终会得到一个丑陋的方法列表,您将向 Liquid 模板公开这些方法。但这样一来,您就确信只有这些方法被公开。
相反,只需添加有关应通过液体暴露的内容的测试。然后您将确保所需的最小值将暴露给 Liquid 模板。
HTH。
I use Liquid and have the same issue. Here is my counsel against your proposed solution:
The entire purpose of Liquid is to not over expose the data or methods of your app to the random people writing the Liquid templates.
(If you will only have trusted people writing the templates, then don't use Liquid. Instead use erb, haml, dryml or other choices.
And if you have two sets of people (trusted and untrusted) then let your trusted people use one type of template and send the untrusted people to Liquid.)
If you expose your methods by default then it is much much harder to test that you haven't exposed too much.
Sure, you end up with an ugly list of methods which you're exposing to the Liquid templates. But that way, you're positive that ONLY those methods are being exposed.
Instead, just add tests about what should be exposed through liquid. Then you'll be sure that the needed minimum will be exposed to the Liquid templates.
HTH.