Module: Datahen::Plugin::ContextExposer

Included in:
Scraper::Executor
Defined in:
lib/datahen/plugin/context_exposer.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.exposed_methodsObject

Raises:

  • (NotImplementedError)


4
5
6
# File 'lib/datahen/plugin/context_exposer.rb', line 4

def self.exposed_methods
  raise NotImplementedError.new('Specify methods exposed to isolated env')
end

Instance Method Details

#create_context(vars = {}) ⇒ Object

Create isolated context object from self



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/datahen/plugin/context_exposer.rb', line 33

def create_context vars = {}
  create_top_object_script = '(
    lambda do
      object = Object.new
      metaclass = class << object
        define_method(:context_binding){binding}
      end
      object
    end
  ).call'
  object = TOPLEVEL_BINDING.eval(create_top_object_script)
  env = exposed_env(vars)
  expose_to object, env
  object
end

#expose_to(object, env) ⇒ Object



24
25
26
27
28
29
30
# File 'lib/datahen/plugin/context_exposer.rb', line 24

def expose_to object, env
  metaclass = class << object; self; end
  env.each do |key, block|
    metaclass.send(:define_method, key, block)
  end
  object
end

#exposed_env(vars) ⇒ Object



19
20
21
22
# File 'lib/datahen/plugin/context_exposer.rb', line 19

def exposed_env vars
  keys = exposed_methods + vars.keys
  Hash[keys.uniq.map{|key|[key, var_or_proc(vars, key)]}]
end

#exposed_methodsObject



8
9
10
# File 'lib/datahen/plugin/context_exposer.rb', line 8

def exposed_methods
  self.class.exposed_methods
end

#isolated_binding(vars = {}) ⇒ Object

Create an isolated binding



50
51
52
# File 'lib/datahen/plugin/context_exposer.rb', line 50

def isolated_binding vars = {}
  create_context(vars).context_binding
end

#var_or_proc(vars, key) ⇒ Object

Create lambda to retrieve a variable or call instance method



13
14
15
16
17
# File 'lib/datahen/plugin/context_exposer.rb', line 13

def var_or_proc vars, key
  myself = self # Avoid stack overflow
  return lambda{vars[key]} if vars.has_key?(key)
  lambda{|*args| myself.send(key, *args)}
end