Class: Validate::AST::Generator

Inherits:
BasicObject
Defined in:
lib/validate/ast.rb

Instance Method Summary collapse

Constructor Details

#initializeGenerator

Returns a new instance of Generator.



83
84
85
# File 'lib/validate/ast.rb', line 83

def initialize
  @stack = []
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args, &block) ⇒ Object (private)



150
151
152
153
154
155
156
157
158
159
160
161
162
# File 'lib/validate/ast.rb', line 150

def method_missing(method, *args, &block)
  return super unless respond_to_missing?(method)

  @stack << [
      :constraint,
      method,
      args.map { |arg| [:value, arg] },
      block,
      ::Kernel.caller
              .reject { |line| line.include?(__FILE__) }
  ]
  self
end

Instance Method Details

#!Object



135
136
137
138
139
140
141
142
143
144
145
146
# File 'lib/validate/ast.rb', line 135

def !
  prev = @stack.pop
  if prev[0] == :no_constraints
    @stack << prev[1]
  elsif prev[0] == :all_constraints
    prev[0] = :no_constraints
    @stack << prev
  else
    @stack << [:no_constraints, prev]
  end
  self
end

#&(other) ⇒ Object



97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
# File 'lib/validate/ast.rb', line 97

def &(other)
  unless other == self
    ::Kernel.raise(
      Error::ValidationRuleError,
      'bad rule, only constraints and &, |, and ! operators allowed'
    )
  end

  right = @stack.pop
  left = @stack.pop
  if right[0] == :all_constraints
    right.insert(1, left)
    @stack << right
  else
    @stack << [:all_constraints, left, right]
  end
  self
end

#generate(*args, &block) ⇒ Object



87
88
89
90
91
92
93
94
95
# File 'lib/validate/ast.rb', line 87

def generate(*args, &block)
  instance_exec(*args, &block)

  if @stack.one? && @stack.first[0] == :all_constraints
    return @stack.first[1..-1]
  end

  @stack
end

#|(other) ⇒ Object



116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
# File 'lib/validate/ast.rb', line 116

def |(other)
  unless other == self
    ::Kernel.raise(
      Error::ValidationRuleError,
      'bad rule, only constraints and &, |, and ! operators allowed'
    )
  end

  right = @stack.pop
  left = @stack.pop
  if right[0] == :at_least_one_constraint
    right.insert(1, left)
    @stack << right
  else
    @stack << [:at_least_one_constraint, left, right]
  end
  self
end