开发者

aliasing find_by methods in rails ActiveRecord

开发者 https://www.devze.com 2023-01-26 07:00 出处:网络
So here\'s the issue, since the find_by methods in AR use the Method Missing technique, you can\'t actually alias them with alias_method (because the method doesn\'t exist!). Or so it seems.

So here's the issue, since the find_by methods in AR use the Method Missing technique, you can't actually alias them with alias_method (because the method doesn't exist!). Or so it seems.

Does anybody know how to do this?

To provide some more detail, what I'm trying to do is this..

I have an AR model, User, but it augments some of it's attributes from a secondary data source -- this should be the default behavior. Initially to achieve this I used the after_find callback, and at that time appended my new attributes from the second data source.

The problem is that I want to be able to occasionally use the find_by methods WITHOUT augmenting from the second data source.

My thought now is t开发者_如何学编程o use aliasing to create two flavors of the find_by methods: find_by and find_without_by.

The ideal would be if rails had some magic sauce that let you use wildcards in alias_method, leading to:

alias_method :find_without*, :find*

any suggestions? I can clarify any specific points if needed.

Thanks in advance!


You could define method_missing in your own models and then pass off to the regular method missing if it is a find_without_abc call:

MyModel < ActiveRecord::Base
  def method_missing(method, *args)
    return super(method, args) if method =~ /find_without/

    # Your custom find code is here...
  end
end
0

精彩评论

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