Confused about 'respond_to' vs 'respond_to?'

后端 未结 3 744
别那么骄傲
别那么骄傲 2021-01-30 02:09

I am learning Rails with railstutorial.org, and I am confused about something: in this chapter the author tells us to do some testing in the console with the respond_to?

3条回答
  •  没有蜡笔的小新
    2021-01-30 02:37

    Ruby treats ? and ! as actual characters in a method name. respond_to and respond_to? are different. ? indicates that this should respond with a true or false (by convention; this is not a requirement). Specifically:

    respond_to? is a Ruby method for detecting whether the class has a particular method on it. For example,

    @user.respond_to?('eat_food')
    

    would return true if the User class has an eat_food method on it.

    respond_to is a Rails method for responding to particular request types. For example:

    def index
      @people = Person.find(:all)
    
      respond_to do |format|
        format.html
        format.xml { render :xml => @people.to_xml }
      end
    end
    

    However, in the RailsTutorial link you've provided, you're seeing an RSpec method should interacting with RSpec's respond_to method. This wouldn't be available in your console, unless you run rails console test.

提交回复
热议问题