File: javascript_behaviour.rb

package info (click to toggle)
ruby-rubyvis 0.6.1%2Bdfsg1-2
  • links: PTS, VCS
  • area: main
  • in suites: buster, stretch
  • size: 1,808 kB
  • ctags: 679
  • sloc: ruby: 11,114; makefile: 2
file content (78 lines) | stat: -rw-r--r-- 1,999 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
class TrueClass
  # Return 1
  def to_i
    1
  end
end
class FalseClass
  # Return 0
  def to_i
    0
  end
end

# :stopdoc:
unless Object.public_method_defined? :instance_exec
  class Object
    module InstanceExecHelper; end
    include InstanceExecHelper
    def instance_exec(*args, &block) # :nodoc:
      begin
        old_critical, Thread.critical = Thread.critical, true
        n = 0
        n += 1 while respond_to?(mname="__instance_exec#{n}")
        InstanceExecHelper.module_eval{ define_method(mname, &block) }
      ensure
        Thread.critical = old_critical
      end
      begin
        ret = send(mname, *args)
      ensure
        InstanceExecHelper.module_eval{ remove_method(mname) } rescue nil
      end
      ret
    end
  end
end
# :startdoc:

# Add javascript-like +apply+ and +call+ methods to Proc,
# called +js_apply+ and +js_call+, respectivly.
class Proc
  # Used on Rubyvis::Nest
  attr_accessor :order # :nodoc:
  
  # Emulation of +apply+ javascript method.
  # +apply+ has this signature
  #   my_proc.apply(my_obj, args)
  # where
  # [+my_proc+] a proc
  # [+my_obj+]  object inside proc is eval'ed
  # [args]      array of arguments for proc
  # 
  # +apply+ on javascript is very flexible. Can accept more or less
  # variables than explicitly defined parameters on lambda, so this
  # method adds or remove elements according to lambda arity
  #
  def js_apply(obj,args)
    arguments=args.dup
    # Modify numbers of args to works with arity
    min_args=self.arity > 0 ? self.arity : (-self.arity)-1
    
    if args.size > min_args and self.arity>0
      arguments=arguments[0,self.arity]
    elsif args.size < min_args
      arguments+=[nil]*(min_args-args.size)
    end
    #puts "#{args}->#{arguments} (#{self.arity})"
    if self.arity==0
        obj.instance_exec(&self)
    else
      obj.instance_exec(*arguments, &self)
    end
  end
  # Same as js_apply, but using explicit arguments
  def js_call(obj, *args)
    js_apply(obj,args)
  end
end