开发者

How can I overwrite an existing instance method from a module in Ruby?

I know I can add new methods to models but I can't seem to overwrite an existing method. Here's what I have

In my User.rb

include ExtraMethods
def is_invisible?
  true unless self.active?
end

In my module

module ExtraMethods
  def self.included(base)
    base.extend(ClassMethods)
  end

  module ClassMethods
    def user_extra_methods
      include ExtraMethods::InstanceMethods
    end
  end
  module InstanceMethods
    def is_invisible?
      true unless self.active? || self.admin?
    end
  end
end

ActiveRecord::Base.send(:include, ExtraMethods)
User.send(:user_extra_methods)

What I want to happen is for the method in the plugin to override the method in the model. Any thoughts or references would be great, can't see开发者_StackOverflow社区m to find a good reference for this.

thanks!

J


The order in which you declare the class members is important.

You're performing the plugin's include before the self.active? method is declared... The model declaration will always take precedence, since it was declared later.

You'll have to resort to something like this:

http://weblog.rubyonrails.org/2006/4/26/new-in-rails-module-alias_method_chain

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜