Paul
Groves
Ltd

Passing instance variables with binding

This example shows how passing Binding to another class provides access to instance variable values.

class Controller
  attr_reader :view_class

  def initialize(view_class: view_class, **options)
    @greeting = options[:greeting]
    @name = options[:name]
    @view_class = view_class
  end

  def render
    view_class.new(binding)
  end
end

class View
  def initialize(binding)
    eval('self.instance_variables', binding).map do |ivar|
      instance_variable_set(ivar, eval(ivar.to_s, binding))
    end
  end

  def to_s
    "View says: #{@greeting} #{@name}!"
  end
end

This can be called with…

puts Controller.new(view_class: View, greeting: 'Oh hello', name: 'Rodney').render