在插件中混淆activerecord方法

时间:2009-09-03 10:00:06

标签: ruby-on-rails ruby activerecord ruby-on-rails-plugins

我正在尝试编写一个插件,以下列方式为ActiveRecord中的某些方法添加别名:

class Foo < ActiveRecord::Base
  include MyOwnPlugin
  acts_as_my_own_plugin :methods => [:bar]

  def bar
    puts 'do something'
  end
end

插件内部:

module MyOwnPlugin
  def self.included(base)    
    base.class_eval do
      extend ClassMethods
    end
  end
  module ClassMethods
    def acts_as_my_own_plugin(options)
      options[:methods].each do |m|
        self.class_eval <<-END
          alias_method :origin_#{m}, :#{m}
        END
      end
    end
  end
end

这种方法不起作用,因为当运行#acts_as_my_own_plugin时,Foo #bar尚未定义,因为它尚未运行。

放置acts_as_my_own_plugin:methods =&gt; [:bar] AFTER 条形函数声明将起作用。但这并不漂亮。

我希望能够将acts_as_my_own_plugin置于类定义之上,就像大多数插件一样。

是否有其他方法可以满足这种条件?

1 个答案:

答案 0 :(得分:5)

永远记住:Ruby中几乎所有内容都有回调。

尝试以下方法:

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

  module ClassMethods
    # gets called from within the models
    def acts_as_my_own_plugin(options)
      # store the list of methods in a class variable and symbolize them
      @@methods = []
      options[:methods].each { |method| @@methods << method.to_sym }
    end

    # callback method. gets called by ruby if a new method is added.
    def method_added(name_of_method)
      if @@methods.include?(name_of_method)
        # delete the current method from our @@methods array
        # in order to avoid infinite loops
        @@methods.delete(name_of_method)
        #puts "DEBUG: #{name_of_method.to_s} has been added!"

        # code from your original plugin
        self.class_eval <<-END
          alias_method :origin_#{name_of_method}, :#{name_of_method}
          def #{name_of_method}
            puts "Called #{name_of_method}"
            origin_#{name_of_method}
          end
        END

      end
    end
  end
end

# include the plugin module in ActiveRecord::Base
# in order to make acts_as_my_own_plugin available in all models 
ActiveRecord::Base.class_eval do
  include MyOwnPlugin
end

# just call acts_as_my_own_plugin and define your methods afterwards
class Foo < ActiveRecord::Base
  acts_as_my_own_plugin :methods => [:bar]

  def bar
    puts 'do something'
  end
end

我希望这很有用。你可以用Ruby做的疯狂事情真是太酷了;)

如果要允许在调用acts_as_my_own_plugin之前和之后定义方法,则需要再次更改代码以允许此操作。然而,困难的部分已经完成。

免责声明:已经使用Ruby 1.8.7进行了测试。可能无法使用Ruby 1.9。*。