_before__与Before_Action保持干燥

_before_

Image for post

A popular mantra when learning Ruby is to be D.R.Y(Don’t Repeat Yourself), we do this in order to avoid looking like our friend Clint Eastwood up above. When building up a Rails application, you find yourself repeating code statements often; especially in your model controllers. Let’s take a look at a few CRUD actions in a controller for a post model within a blog application :

学习Ruby时的一种流行口号是DRY(不要重复自己),我们这样做是为了避免看起来像我们的朋友Clint Eastwood一样。 在构建Rails应用程序时,您会发现自己经常重复执行代码语句。 特别是在您的模型控制器中。 让我们看一下博客应用程序中用于帖子模型的控制器中的一些CRUD操作:

Image for post

As you can see, we are already repeating ourselves in the actions ‘show’, ‘edit’, ‘update’, and ‘destroy’ in the very first line of each action . In each of these methods we are calling:

如您所见,我们已经在每个动作的第一行中对动作“显示”,“编辑”,“更新”和“破坏”进行了重复。 在每种方法中,我们都在调用:

@post = Post.find(params[:id]

to acquire a post instance. To D.R.Y our code up in the controller, we can add a controller filter that is run prior to each action. Filters are methods that can be run before, after, or around controller actions. For the purpose of this instance, we want to use a “before” filter since we want this code to run before our actions.

获取帖子实例。 要在控制器中干燥我们的代码,我们可以添加在每个操作之前运行的控制器过滤器。 过滤器是可以在控制器操作之前,之后或周围运行的方法。 就此实例而言,我们希望使用“之前”过滤器,因为我们希望此代码操作之前运行。

Creating The Helper Method

创建助手方法

Before implementing our before_action filter , we need to establish a helper method under ‘private’ that contains the code we are repeating:

在实现before_action过滤器之前,我们需要在“ private”下建立一个包含要重复的代码的辅助方法:

Image for post

We can name the helper method something simple such as ‘find_post’.

我们可以将辅助方法命名为简单的名称,例如“ find_post”。

Before_Action Syntax

Before_Action语法

Now that we have our helper method established, we can implement our before_action filter on the first line of our controller. The syntax is shown below:

现在,我们已经建立了辅助方法,我们可以在控制器的第一行上实现before_action过滤器。 语法如下所示:

Image for post

After calling our helper method, we specify which controller actions we want this to be called on:

调用了辅助方法之后,我们指定希望调用哪个控制器动作:

only [:show, :edit, :update, :destroy]

This now lets our controller know that before carrying out these actions, we want to run ‘find_post’ in our show, edit, update, and destroy actions without explicitly writing it out. Awesome!

现在,这使我们的控制器知道在执行这些操作之前,我们希望在显示,编辑,更新和销毁操作中运行“ find_post”,而无需明确地将其写出。 太棒了!

Hopefully now you can stay a little dryer out there in the programming world.

希望现在您可以在编程世界中呆一些。

For more documentation on controller filters here!

有关此处的控制器过滤器的更多文档!

翻译自: https://medium.com/@dr.lucasleibs/staying-d-r-y-with-before-action-c13ea1482832

_before_

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值