是否可以在 Ruby 中执行 before_action(如在 Rails 中)? [英] Is it possible to do a before_action in Ruby (like in Rails)?

查看:45
本文介绍了是否可以在 Ruby 中执行 before_action(如在 Rails 中)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在 Rails 等指定方法之前调用 before_action ?

Is it possible to call a before_action before some specified method like in rails?

class Calculator
  before_action { raise Exception, "calculator is empty" if @numbers.nil? }, 
                 only: [:plus, :minus, :divide, :times]

  def push number
    @numbers ||= [] 
    @numbers << number
  end

  def plus
    # ... 
  end

  def minus
    # ... 
  end

  def divide
    # ... 
  end

  def times
    # ... 
  end

    # ... 
end

推荐答案

您正在寻找的是 面向方面的编程 支持 ruby​​.有几个 gem 实现了这一点,例如 aquarium.

What you are looking for is Aspect oriented programming support for ruby. There are several gems implementing this, like aquarium.

不过,我认为,在您的情况下,一些懒惰的检查就足够了:

I think though, that in your case, some lazy checks will be sufficient:

class Calculator
  def numbers
    raise Exception, "calculator is empty" if @numbers.nil?
    @numbers
  end

  def push number
    @numbers ||= [] 
    @numbers << number
  end

  def plus
    numbers.inject(:+) # <-- will throw the correct Exception if `@numbers` is nil
    # ... 
  end

  def minus
    # ... 
  end

  def divide
    # ... 
  end

  def times
    # ... 
  end

    # ... 
end

这篇关于是否可以在 Ruby 中执行 before_action(如在 Rails 中)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆