开发者

Respond_to in combination with aliassing a method in Rails

In a plugin I am writing I am using alias to override one of the default Rails validators like so:

# Alias the original validator so it's still available under a different name
alias original_validates_uniqueness_of :validates_uniqueness_of unless method_defined?(:original_validates_uniqueness_of)
# Then alias the custom validator under the original name
alias validates_uniqueness_of :custom_validates_uniqu开发者_如何学Ceness_of

This all works pretty well. When "validates_uniqueness_of" is defined on an attribute in a AR model, it will use my "custom_validates_uniqueness_of" method instead. Validations are running as expected.

However, when I call:

SomeARclass.respond_to?(:validates_uniqueness_of)

..it will return false. This behavior will mess with several popular plugins.

My question:

Why is respond_to returning "false"? Is this behavior the result of alliasing? How can adjust my custom validator to make it return true?

Thank you for your help.

Erwin


Your sample, on the surface, looks like it should work. I expect you've found that, inside of the class body for class SomeARclass, you actually can call validates_uniqueness_of.

class SomeARclass
  validates_uniqueness_of :first_field # works
end

However, I expect that scoped_validates_uniqueness_of is a private method. That's why you have been unable to send that message to SomeARclass from outside of its class body.

SomeARclass.validates_scoped_uniqueness_of :first_field # fails
#=> NoMethodError: private method "validates_scoped_uniqueness_of" called
    for SomeARclass:Class

When you alias a private method with a new name, such as aliasing the private method validates_scoped_uniqueness_of with the new name validates_uniqueness_of, then that new method is also private. I expect that's what happened here.

The documentation for #respond_to? reads:

- (Boolean) respond_to?(symbol, include_private = false)

Returns true if obj responds to the given method. Private methods are included in the search only if the optional second parameter evaluates to true.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜