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:
SimpleDelegator
if you want to wrap an object & expose all of its methods