Ruby: How do I pass all parameters and blocks received by one method to another?

前端 未结 2 536
没有蜡笔的小新
没有蜡笔的小新 2021-02-02 06:18

I am writing a helper that adds an HTML attribute to a link_to tag in rails. So, my thinking is that my helper method should accept any parameters or blocks passed to it, call l

相关标签:
2条回答
  • 2021-02-02 06:47

    def method(...)

    Starting from Ruby 2.7 it is possible to pass all the arguments of the current method to the other method using (...).

    So, now,

    def my_helper(*args, &block)
      link_to(*args, &block)
      
      # your code
    end
    

    can be rewritten as

    def my_helper(...)
      link_to(...)
    
      # your code
    end
    

    Here is the link to the feature request.

    0 讨论(0)
  • 2021-02-02 07:01

    You can use * and & in method calls to turn arrays back into lists of arguments and procs back into blocks. So you can just do this:

    def myhelper(*args, &block)
      link_to(*args, &block)
      # your code
    end
    
    0 讨论(0)
提交回复
热议问题