红宝石类方法与装饰器

时间:2019-01-16 07:49:26

标签: ruby decorator

我想使用instant_methodclass_method分别创建类,如下所示:

module ObjReviewModule  ## common methods module
  def own_methods(obj_)
    ruby_methods = " ".methods & 1.methods
    (obj_.methods - ruby_methods).map { |x| x.to_s }
  end

  def specific_methods(obj_,existing_=[])
    self.own_methods(obj_).select { |x| !existing_.include?(x) }
  end
end

class ObjReviewMethod ## instance_method 
  include ObjReviewModule 

  def get_(obj_)
    own_methods(obj_).select { |x| x.start_with?("get") }
  end

  def to_(obj_)
    own_methods(obj_).select{ |x| x.start_with?("to_") }
  end
end

class ObjList < OsObjReviewMethod ## class_method 
  extend ObjReviewModule

  def self.get_methods(obj_)
    # something should be here to make OsObjReviewMethod instance_method became class_method
  end
end

我得到ObjReviewMethod的工作

object_methods = ObjReviewMethod.new
object_methods.get_(obj_) => get "own_methods" start with "get" using instance_class_method
ObjList.own_methods(obj_) => get "own_methods" with class_method

但是我不知道如何在不重写所有定义的情况下获得class_method

ObjList.get_methods(obj_) => get all "own_methods" start with "get" using class_method

如果装饰器类可以将基类的所有instance_method用作class_method

,那将是完美的选择

1 个答案:

答案 0 :(得分:0)

如下所示的解决方案

module ObjReviewModule  ## common methods module
  def own_methods(obj_)
    ruby_methods = " ".methods & 1.methods
    (obj_.methods - ruby_methods).map { |x| x.to_s }
  end

  def specific_methods(obj_,existing_=[])
    self.own_methods(obj_).select { |x| !existing_.include?(x) }
  end
end

module ObjReviewMethod 
  include ObjReviewModule 
  def get_(obj_)
    own_methods(obj_).select { |x| x.start_with?("get") }
  end
  def to_(obj_)
    own_methods(obj_).select{ |x| x.start_with?("to_") }
  end
end

class ObjList ## class_method 
  extend ObjReviewModule
  extend ObjReviewMethod
end

class ObjReview ## instance_method 
  include ObjReviewModule
  include ObjReviewMethod
end