Class: Sunshine::Binder

Inherits:
Object
  • Object
show all
Defined in:
lib/sunshine/binder.rb

Overview

Create a selective binding. Useful for controlling ERB builds:

binder.set :server_name, "blah.com"
binder.forward :server_method, ...
binder.get_binding

Instance Method Summary collapse

Constructor Details

#initialize(target) ⇒ Binder

Returns a new instance of Binder.



11
12
13
# File 'lib/sunshine/binder.rb', line 11

def initialize target
  @target = target
end

Instance Method Details

#forward(*method_names) ⇒ Object

Forward a method to the server instance.



50
51
52
53
54
55
56
57
58
59
# File 'lib/sunshine/binder.rb', line 50

def forward *method_names
  method_names.each do |method_name|
    instance_eval "    undef \#{method_name} if defined?(\#{method_name})\n    def \#{method_name}(*args, &block)\n      @target.\#{method_name}(*args, &block)\n    end\n    STR\n  end\nend\n", __FILE__, __LINE__ + 1

#get_bindingObject

Retrieve the object’s binding.



65
66
67
# File 'lib/sunshine/binder.rb', line 65

def get_binding
  binding
end

#import_hash(hash) ⇒ Object

Takes a hash and assign each hash key/value as an attribute.



42
43
44
# File 'lib/sunshine/binder.rb', line 42

def import_hash hash
  hash.each{|k, v| self.set(k, v)}
end

#set(key, value = nil, &block) ⇒ Object

Set the binding instance variable and accessor method.



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/sunshine/binder.rb', line 19

def set key, value=nil, &block
  value ||= block if block_given?

  instance_variable_set("@#{key}", value)

  eval_str = "    undef \#{key} if defined?(\#{key})\n    def \#{key}(*args)\n      if Proc === @\#{key}\n        @\#{key}.call(*args)\n      else\n        @\#{key}\n      end\n    end\n  STR\n\n  instance_eval eval_str, __FILE__, __LINE__ + 1\nend\n"