Class: String

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

Instance Method Summary collapse

Instance Method Details

#to_proc(&block) ⇒ Object



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
# File 'lib/ruleby.rb', line 26

def to_proc &block
  params = []
  expr = self
  sections = expr.split(/\s*->\s*/m)
  if sections.length > 1 then
      eval sections.reverse!.inject { |e, p| "(Proc.new { |#{p.split(/\s/).join(', ')}| #{e} })" }, block && block.binding
  elsif expr.match(/\b_\b/)
      eval "Proc.new { |_| #{expr} }", block && block.binding
  else
      leftSection = expr.match(/^\s*(?:[+*\/%&|\^\.=<>\[]|!=)/m)
      rightSection = expr.match(/[+\-*\/%&|\^\.=<>!]\s*$/m)
      if leftSection || rightSection then
          if (leftSection) then
              params.push('$left')
              expr = '$left' + expr
          end
          if (rightSection) then
              params.push('$right')
              expr = expr + '$right'
          end
      else
          self.gsub(
              /(?:\b[A-Z]|\.[a-zA-Z_$])[a-zA-Z_$\d]*|[a-zA-Z_$][a-zA-Z_$\d]*:|self|arguments|'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"/, ''
          ).scan(
            /([a-z_$][a-z_$\d]*)/i
          ) do |v|  
            params.push(v) unless params.include?(v)
          end
      end
      eval "Proc.new { |#{params.join(', ')}| #{expr} }", block && block.binding
  end
end