Class: Marty::RuleScriptSet

Inherits:
Delorean::AbstractContainer
  • Object
show all
Defined in:
lib/marty/rule_script_set.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(pt) ⇒ RuleScriptSet

Returns a new instance of RuleScriptSet.



22
23
24
25
26
27
28
29
# File 'lib/marty/rule_script_set.rb', line 22

def initialize(pt)
  @pt = Mcfly.normalize_infinity(pt)

  # if pt is Infinity, we get a DEV Tag
  tag = Marty::Tag.cached_find_match(pt)
  @sset = Marty::ScriptSet.new(tag)
  super()
end

Instance Attribute Details

#ptObject (readonly)

Returns the value of attribute pt.



2
3
4
# File 'lib/marty/rule_script_set.rb', line 2

def pt
  @pt
end

#ssetObject (readonly)

Returns the value of attribute sset.



2
3
4
# File 'lib/marty/rule_script_set.rb', line 2

def sset
  @sset
end

Class Method Details

.body_linesObject



18
19
20
# File 'lib/marty/rule_script_set.rb', line 18

def self.body_lines
  body_start.count("\n")
end

.body_startObject



14
15
16
# File 'lib/marty/rule_script_set.rb', line 14

def self.body_start
  "#{node_name}:\n"
end

.clear_cacheObject



4
5
6
# File 'lib/marty/rule_script_set.rb', line 4

def self.clear_cache
  @@engines, @@dengines, @@dengines_dt = {}, {}, nil
end

.grid_final_name(dgid) ⇒ Object



44
45
46
# File 'lib/marty/rule_script_set.rb', line 44

def self.grid_final_name(dgid)
  dgid.ends_with?('_grid') ? dgid + '_result' : dgid + '_grid_result'
end

.indent(s) ⇒ Object



206
207
208
# File 'lib/marty/rule_script_set.rb', line 206

def self.indent(s)
  s.gsub(/^/, ' ' * 4)
end

.node_nameObject



10
11
12
# File 'lib/marty/rule_script_set.rb', line 10

def self.node_name
  'Node'
end

Instance Method Details

#code_section_counts(ruleh) ⇒ Object



120
121
122
123
124
125
126
127
# File 'lib/marty/rule_script_set.rb', line 120

def code_section_counts(ruleh)
  errs = {}
  errs[:grid_params] = grid_init(ruleh).count("\n")
  errs[:computed_guards] = guard_code(ruleh).count("\n")
  errs[:grids] = grid_code(ruleh).count("\n")
  errs[:results] = result_code(ruleh).count("\n")
  errs
end

#expand_grid_code(h, dgid, dgname, cache, _extra_params) ⇒ Object



48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/marty/rule_script_set.rb', line 48

def expand_grid_code(h, dgid, dgname, cache, _extra_params)
  final_name = self.class.grid_final_name(dgid)
  if cache[dgname]
    h[final_name] = (cache[dgname]).to_s
  else
    h[dgid] = dgname
    h["#{dgid}_dgp__"] = "dgparams__ + \n" + self.class.indent(paramify_h(h))
    lgde = 'lookup_grid_h'
    h[final_name] = "Marty::DataGrid.#{lgde}(pt,#{dgid},#{dgid}_dgp__,true)"
    cache[dgname] = final_name
  end
end

#get_code(ruleh) ⇒ Object



103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
# File 'lib/marty/rule_script_set.rb', line 103

def get_code(ruleh)
  grid_i = grid_init(ruleh)
  grid_c = grid_code(ruleh)
  result_c = result_code(ruleh)
  guard_c = guard_code(ruleh)

  code = self.class.body_start +
         self.class.indent(grid_i + guard_c + grid_c + result_c)
  # puts '='*40
  # puts ruleh["name"]
  # puts '-'
  # puts code
  # puts '-'*10

  code
end

#get_engine(ruleh) ⇒ Object



158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
# File 'lib/marty/rule_script_set.rb', line 158

def get_engine(ruleh)
    # if rule is a str => importing a regular Script (i.e. not rule)
    return sset.get_engine(ruleh) if ruleh.is_a? String

    # on create rule doesn't have an id => don't cache
    return sset.parse_check("New RULE #{ruleh['name']}", get_code(ruleh)) unless
      ruleh['id']

    rule_pfx = ruleh['classname'].demodulize

    # unique name for specific version of rule
    sname = "#{rule_pfx}_#{ruleh['group_id']}_#{ruleh['created_dt'].to_f}"

    # is it a dev posting?
    if Mcfly.is_infinity(pt)
      max_dt = ruleh['classname'].constantize.order('created_dt DESC').
               limit(1).pluck(:created_dt).first

      @@dengines_dt ||= max_dt

      # reset dengine cache if an rule has changed
      @@dengines = {} if max_dt > @@dengines_dt

      engine = @@dengines[sname]

      return engine if engine

      @@dengines[sname] = sset.parse_check(sname, get_code(ruleh))
    else
      engine = @@engines[[pt, sname]]

      return engine if engine

      @@engines[[pt, sname]] = sset.parse_check(sname, get_code(ruleh))
    end
rescue Delorean::ParseError => e
    secnm, attr_or_line = get_parse_error_field(ruleh, e)
    msg = e.message.capitalize
    field = secnm ? "field '#{secnm}'" : ''
    where = if attr_or_line.is_a?(String)
            then "(attribute #{attr_or_line})"
            elsif attr_or_line.is_a?(Integer)
            then "(line #{attr_or_line})"
            else ''
            end
    raise "Error in rule '#{ruleh['name']}' #{field} #{where}: #{msg}"
end

#get_parse_error_field(ruleh, exc) ⇒ Object



140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
# File 'lib/marty/rule_script_set.rb', line 140

def get_parse_error_field(ruleh, exc)
  line = (exc.line || 1) - 1
  errs = { class_body: self.class.body_lines } + code_section_counts(ruleh)
  secnm, line_in_sec = search_ranges(errs, line)
  if [:computed_guards, :results].include?(secnm)
    h = Hash[ruleh[secnm.to_s].map { |k, v| [k, v.lines.count + 1] }]
    attrnm, = search_ranges(h, line_in_sec)
  end
  [secnm, attrnm || line_in_sec]
rescue StandardError => e
  Marty::Logger.error('RuleScriptSet#get_parse_error_field',
                      error: e.message,
                      backtrace: e.backtrace,
                      ruleh: ruleh,
                      line: line)
  [nil, nil]
end

#grid_code(ruleh) ⇒ Object



74
75
76
77
78
79
80
81
82
# File 'lib/marty/rule_script_set.rb', line 74

def grid_code(ruleh)
  dgcache = {}
  h = {}
  ruleh['grids'].each do |k, v|
    expand_grid_code(h, k.ends_with?('_grid') ? k : k + '_grid', %Q("#{v}"),
                     dgcache, {})
  end
  h.map { |k, v| write_attr(k, v) }.join("\n") + "\n"
end

#grid_init(ruleh) ⇒ Object



92
93
94
95
96
97
98
99
100
101
# File 'lib/marty/rule_script_set.rb', line 92

def grid_init(ruleh)
  if ruleh['grids'].present? ||
     ruleh['results'].keys.any? { |k| k.ends_with?('_grid') }
    write_code('pt' => :parameter,
                 'dgparams__' => :parameter,
              )
  else
    ''
  end
end

#guard_code(ruleh) ⇒ Object



84
85
86
# File 'lib/marty/rule_script_set.rb', line 84

def guard_code(ruleh)
  write_code(ruleh['computed_guards'])
end

#paramify_h(h) ⇒ Object



39
40
41
42
# File 'lib/marty/rule_script_set.rb', line 39

def paramify_h(h)
  '{' + h.keys.reject { |k| k.ends_with?('__') }.
                       map { |k| %Q("#{k}": #{k}) }.join(",\n") + '}'
end

#result_code(ruleh) ⇒ Object



88
89
90
# File 'lib/marty/rule_script_set.rb', line 88

def result_code(ruleh)
  write_code(ruleh['results'])
end

#search_ranges(oh, line) ⇒ Object



129
130
131
132
133
134
135
136
137
138
# File 'lib/marty/rule_script_set.rb', line 129

def search_ranges(oh, line)
  ranges0 = oh.values.reduce([0]) do |acc, len|
    acc + [acc.last + len]
  end
  ranges = oh.keys.zip(ranges0.each_cons(2).to_a)
  secnm, (st, en) = ranges.detect do |_sec, (st, en)|
    line.between?(st, en - 1)
  end
  [secnm, line - st + 1]
end

#write_attr(k, v) ⇒ Object



33
34
35
36
37
# File 'lib/marty/rule_script_set.rb', line 33

def write_attr(k, v)
  equals, rhs = v == :parameter ? [' =?', ''] :
                  [" =\n", v.lines.map { |l| ' ' * 8 + l }.join]
  k + equals + rhs
end

#write_code(attrs) ⇒ Object



61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/marty/rule_script_set.rb', line 61

def write_code(attrs)
  return '' if attrs.blank?

  newh = attrs.each_with_object({}) do |(k, v), h|
    if k.ends_with?('_grid')
      expand_grid_code(h, k, v, {}, h)
    else
      h[k] = v
    end
  end
  newh.map { |k, v| write_attr(k, v) }.join("\n") + "\n"
end