【问题标题】:How to comment Multiple lines in rails 5 controller?如何评论 Rails 5 控制器中的多行?
【发布时间】:2016-12-02 19:13:44
【问题描述】:

我正在尝试在 Rails 5 控制器中注释多行,我在网上搜索并找到了以下解决方案:“=begin”

=begin (Multiple lines)
      respond_to do |format|
       if @person.update_attributes(params[:person])
        flash[:notice] = 'Person was successfully updated.'
        format.html { redirect_to(@person) }
        format.xml { head :ok }
       else
        format.html { render :action => "edit" }
        format.xml { render :xml => @person.errors, :status => :unprocessable_entity }
       end
      end
=end

但它给出了这个错误:

语法错误,意外的 '=' =begin

我正在使用 Rails 5.0。

【问题讨论】:

    标签: ruby-on-rails ruby


    【解决方案1】:

    除了其他答案之外,Ruby 中的多行注释语法虽然存在,但很少使用。一些编辑器和语法荧光笔甚至无法识别它。最好的办法是在每条注释行上使用#

    使用# 的另一个好处是可以嵌套cmets,而=begin ... =end 语法则无法做到这一点。

    respond_to do |format|
      if @person.update_attributes(params[:person])
        #  top level commented block
        #  flash[:notice] = 'Person was successfully updated.'
        #  # second level commented block
        #  # format.html { redirect_to(@person) }
        #  # format.xml { head :ok }
        # ...
      end
    end
    

    您的 IDE 一次注释/取消注释单个注释级别应该没有问题。

    请参阅this SO question 进行讨论。

    【讨论】:

    • 嗯,但是如果我们处理一个巨大的代码,那么注释每一行并不是一个好主意,会浪费很多时间
    • 您应该使用 IDE 的工具,而不是手动键入每个符号。多行注释快捷方式基本上随处可用。
    【解决方案2】:

    =begin=end 前面不能有任何空格

    =begin
      code 
      I 
      want
      to 
      comment
    =end
    

    这类似于用#注释每一行

    # code 
    # I 
    # want
    # to 
    # comment
    

    【讨论】:

      【解决方案3】:

      Ruby 多行 cmets 仅在行首和 =begin 之间没有空格时才起作用(同样适用于 =end)。确保该行以=begin: 开头:

      这行得通:

      =begin
        foo
        bar
      =end
      

      这行不通:

        =begin
          foo
          bar
        =end
      

      【讨论】:

        【解决方案4】:

        =begin 和 =end 应该在类的相同缩进级别。如下所示

        class MyController < ApplicationController
        =begin
        =end
        end
        

        【讨论】:

        • 这不太正确。注释标记的= 必须是行中的第一个符号,无论这是否发生在类的代码中。
        • 我同意 Nic Nilov,尽管 Sven Koschnicke 解释得更好
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-04-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-09-04
        • 1970-01-01
        相关资源
        最近更新 更多