ruby 为任意Ruby类提供类似ActiveRecord的before_filter功能

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ruby 为任意Ruby类提供类似ActiveRecord的before_filter功能相关的知识,希望对你有一定的参考价值。

# First the end result of what we want:

class Foo
  before_hook :whoa
  before_hook :amazing

  def test
    puts "This is kinda cool!"
  end

  def amazing
    puts "Pretty amazing!"
  end

  def whoa
    puts "Whoa!"
  end
end

Foo.new.test

# OUTPUT BELOW

Whoa!
Pretty amazing!
This is kinda cool!

# And this is how I implemented it:

# Demonstrates how to provide ActiveRecord-like before_filter
# hooks for arbitrary classes.

module ExecutionHooks
  # this method is invoked whenever a new instance method is added to a class
  def method_added(method_name)
    # do nothing if the method that was added was an actual hook method, or
    # if it already had hooks added to it
    return if hooks.include?(method_name) || hooked_methods.include?(method_name)
    add_hooks_to(method_name)
  end

  # this is the DSL method that classes use to add before hooks
  def before_hook(method_name)
    hooks << method_name
  end

  # keeps track of all before hooks
  def hooks
    @hooks ||= []
  end

  private

  # keeps track of all currently hooked methods
  def hooked_methods
    @hooked_methods ||= []
  end

  def add_hooks_to(method_name)
    # add this method to known hook mappings to avoid infinite
    # recursion when we redefine the method below
    hooked_methods << method_name

    # grab the original method definition
    original_method = instance_method(method_name)

    # re-define the method, but notice how we reference the original
    # method definition
    define_method(method_name) do |*args, &block|
      # invoke the hook methods
      self.class.hooks.each do |hook|
        method(hook).call
      end

      # now invoke the original method
      original_method.bind(self).call(*args, &block)
    end
  end
end

# Make it available to all classes.
Class.send(:include, ExecutionHooks)

以上是关于ruby 为任意Ruby类提供类似ActiveRecord的before_filter功能的主要内容,如果未能解决你的问题,请参考以下文章

包含 Ruby on Rails 内容的播放列表

Rails 框架上的 Ruby CGI 代码

Ruby Socket 编程

ruby File类

Ruby 数据库访问 - DBI 教程

Ruby on Rails Rake在将rails项目从4.1.9更新到4.2.0后抛出“不正确的表名”错误