What are delegate, delegate method, SimpleDelegator in ruby

 delegate methods in Rails, exposing only necessary methods of containing objects, thereby, making them more easily accessible.

class Parent
  def initialize
    @child = Child.new
  end
end

class Child
  def initialize
    @data = []
  end

  def insert(data)
    @data << data
  end

  def fetch(key)
    @data[key]
  end
end

parent = Parent.new

if you try this

parent.insert("imrahul")

then you will get response

undefined method `insert' for #<Parent:0x000055f4915673a0 @child=#<Child:0x000055f491567350 @data=[]>> (NoMethodError) 


This code will work if we overide methods of child class


class Parent

  def initialize

    @child = Child.new

  end

  def insert(data)

    @child.insert(data)

  end

  def fetch(index)

    @child.fetch(index)

  end

end


class Child

  def initialize

    @data = []

  end


  def insert(data)

    @data << data

  end


  def fetch(key)

    @data[key]

  end

end


parent = Parent.new

parent.insert("imrahul")

So this is how delegate works, delegate needs target object to expose

You can use the Forwardable module included with Ruby to define delegator methods.

It works like this:

require 'forwardable'
class Parent
extend Forwardable
def_delegators :@child, :insert, :fetch
def initialize
@child = Child.new
end end class Child   def initialize @data = [] end def insert(data) @data << data end def fetch(key) @data[key] end end

















class Parent
delegate :fetch, :insert, to: :@child
def initialize
@child = Child.new
end
end

SimpleDelegator

 if you want to wrap an object & expose all of its methods

require 'delegate'
class SampleArr < SimpleDelegator
end
sample = SampleArr.new([])
sample << "im"
sample << "rahul"
p sample




Popular posts from this blog

DmL command || Sql Tutorial -7

Wicked-PDF not showing images, 'wicked_pdf_image_tag' undefined