KoU_warch
KoU_warch

Reputation: 2150

Rails react to a false respond_to?

I'm trying to return something if a method does not exist in rails.

The ruby model that i have looks like this:

class myModel

  attr_accessible :attr_a, :attr_b, #name of attributes `attr_c` and `attr_d`
                  :attr_c, :attr_d  #are equal to `method_c` and `method_d` names
  #init some values
  after_initialize :default_values

  def default_values
    self.is_active ||= true
    self.attr_a ||= 'None'
    self.attr_b ||= 1
    if !self.respond_to?("method_c")
      #return something if the method is called
      self.method_c = 'None' #not working
    end
    if !self.respond_to?("method_d")
      #return something if the method is called
      self.method_d = 'None' #not working
    end
  end

  #more methods
end

however i'm getting an error in my spec tests:

   NoMethodError:
     undefined method `method_c' for #<Object:0xbb9e53c>

I know it sounds crazy but, what can i do to return something if the method does not exist?

Upvotes: 0

Views: 57

Answers (1)

Chris Heald
Chris Heald

Reputation: 62698

Ruby has an excellent construct called #method_missing which is called whenever a message is sent to an object which doesn't handle that method. You can use it to dynamically handle methods by method name:

class MyModel

  attr_accessible :attr_a, :attr_b, #name of attributes `attr_c` and `attr_d`
                  :attr_c, :attr_d  #are equal to `method_c` and `method_d` names
  #init some values
  after_initialize :default_values

  def default_values
    self.is_active ||= true
    self.attr_a    ||= 'None'
    self.attr_b    ||= 1
  end

  def method_missing(method, *args)
    case method
    when :method_c
      attr_c = "None"   # Assigns to attr_c and returns "None"
    when :method_d
      attr_d = "None"   # Assigns to attr_d and returns "None"
    else
      super             # If it wasn't handled, then just pass it on, which will result in an exception.
    end
  end
end

Upvotes: 2

Related Questions