开发者

Passthrough Methods

Does anyone know of a way of providing pass-through methods to provide something like the following but with added DRY?

class Cover开发者_开发技巧

  @some_class = SomeClass.new

  def some_method
    @some_class.some_method
  end

end

ideally I would like to dry it up to something like this:

class Cover

  @some_class = SomeClass.new
  passthrough @some_class.some_method

end

without monkey-patching the life out of myself is there anything people have?

Cheers,

Roja


Support for the Delegation Pattern


Delegate


Does the Delegate help here? It allows you to delegate methods to a second class

This library provides three different ways to delegate method calls to an object. The easiest to use is SimpleDelegator. Pass an object to the constructor and all methods supported by the object will be delegated. This object can be changed later.

Going a step further, the top level DelegateClass method allows you to easily setup delegation through class inheritance. This is considerably more flexible and thus probably the most common use for this library.

Finally, if you need full control over the delegation scheme, you can inherit from the abstract class Delegator and customize as needed. (If you find yourself needing this control, have a look at forwardable, also in the standard library. It may suit your needs better.)


Forwardable


There's also the forwardable library

This library allows you delegate method calls to an object, on a method by method basis. You can use Forwardable to setup this delegation at the class level, or SingleForwardable to handle it at the object level.


Forwadable is probably what you want:

class Cover
  extend Forwardable

  def initialize
     @some_class = SomeClass.new
  end

  def_delegator @some_class, :some_method

end

Forwardable works on a class level, but you can also use SingleForwardable for object level delegation.


Two ways, one pure ruby, one Rails.

Ruby: def_delegator from Forwardable http://ruby-doc.org/stdlib/libdoc/forwardable/rdoc/classes/Forwardable.html

Rails: delegate http://api.rubyonrails.org/classes/Module.html#M000110


You can override the kernel's method_missing like so:

class Bar
  def method_missing(method, *args)
    @delegate.send(method, *args) if @delegate.respond_to? method
  end
end
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜