Class: Marty::DataGrid

Inherits:
Base show all
Defined in:
app/models/marty/data_grid.rb,
app/services/marty/data_grid/constraint.rb

Defined Under Namespace

Classes: Constraint, DataGridValidator

Constant Summary collapse

DEFAULT_DATA_TYPE =

If data_type is nil, assume float

'float'
INDEX_MAP =
{
  'numrange'  => Marty::GridIndexNumrange,
  'int4range' => Marty::GridIndexInt4range,
  'integer'   => Marty::GridIndexInteger,
  'string'    => Marty::GridIndexString,
  'boolean'   => Marty::GridIndexBoolean,
}.freeze
ARRSEP =
'|'.freeze
NOT_STRING_START =
'NOT ('.freeze
NOT_STRING_END =
')'.freeze
NULL_STRING =
'NULL'.freeze
PLV_DT_FMT =
'%Y-%m-%d %H:%M:%S.%N6'

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Base

get_final_attrs, make_hash, make_openstruct, mcfly_pt

Methods inherited from ActiveRecord::Base

joins, old_joins

Class Method Details

.clear_dtcacheObject



182
183
184
# File 'app/models/marty/data_grid.rb', line 182

def self.clear_dtcache
  @@dtcache = {}
end

.convert_data_type(data_type) ⇒ Object



171
172
173
174
175
176
177
178
179
180
# File 'app/models/marty/data_grid.rb', line 171

def self.convert_data_type(data_type)
  # given data_type, convert it to class and or known data type --
  # returns nil if data_type is invalid

  return DEFAULT_DATA_TYPE if data_type.nil?
  return data_type if
    Marty::DataConversion::DATABASE_TYPES.member?(data_type.to_sym)

  data_type.constantize rescue nil
end

.create_from_import(name, import_text, created_dt = nil) ⇒ Object



819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
# File 'app/models/marty/data_grid.rb', line 819

def self.create_from_import(name, import_text, created_dt = nil)
  parsed_result = parse(created_dt, import_text, {})

   = parsed_result[:metadata]
  data = parsed_result[:data]
  data_type = parsed_result[:data_type]
  lenient = parsed_result[:lenient]
  constraint = parsed_result[:constraint]
  strict_null_mode = parsed_result[:strict_null_mode]

  dg                  = new
  dg.name             = name
  dg.data             = data
  dg.data_type        = data_type
  dg.lenient          = lenient
  dg.strict_null_mode = strict_null_mode
  dg.         = 
  dg.created_dt       = created_dt if created_dt
  dg.constraint       = constraint
  dg.save!
  dg
end

.export_keys(inf) ⇒ Object



484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
# File 'app/models/marty/data_grid.rb', line 484

def self.export_keys(inf)
  # should unify this with Marty::DataConversion.convert

  type = inf['type']
  nots = inf.fetch('nots', [])
  wildcards = inf.fetch('wildcards', [])
  klass = type.constantize unless INDEX_MAP[type]

  keys = inf['keys'].each_with_index.map do |v, index|
    wildcard = wildcards.fetch(index, true)

    next 'NULL' if v.nil? && !wildcard

    case type
    when 'numrange', 'int4range'
      Marty::Util.pg_range_to_human(v)
    when 'boolean'
      v.to_s
    when 'string', 'integer'
      v.map do |val|
        next 'NULL' if val.nil? && !wildcard

        val.to_s
      end.join(ARRSEP) if v
    else
      # assume it's an AR class
      v.each do |k|
        begin
          # check to see if class instance actually exists
          Marty::DataGrid.
            find_class_instance('infinity', klass, k) || raise(NoMethodError)
        rescue NoMethodError
          raise "instance #{k} of #{type} not found"
        end
      end if v
      v.join(ARRSEP) if v
    end
  end

  keys.each_with_index.map do |v, index|
    next v unless nots[index]

    add_not(v)
  end
end

.get_struct_attrsObject



119
120
121
# File 'app/models/marty/data_grid.rb', line 119

def self.get_struct_attrs
  self.struct_attrs ||= super + ['id', 'group_id', 'created_dt', 'name']
end

.lookup_grid_distinct_entry_h(pt, h, dgh, visited = nil, follow = true, return_grid_data = false, distinct = true) ⇒ Object



425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
# File 'app/models/marty/data_grid.rb', line 425

def self.lookup_grid_distinct_entry_h(
  pt, h, dgh, visited = nil, follow = true,
  return_grid_data = false, distinct = true
)

  # Perform grid lookup, if result is another data_grid, and follow is true,
  # then perform lookup on the resulting grid.  Allows grids to be nested
  # as multi-grids.  If return_grid_data is true, also return the grid
  # data and metadata
  # return is a hash for the grid results:
  #
  #   "result"   => <result of running the grid>
  #   "name"     => <grid name>
  #   "data"     => <grid's data array>
  #   "metadata" => <grid's metadata (array of hashes)>

  vhash = if Rails.application.config.marty.data_grid_plpg_lookups &&
             Rails.env.test? # Keep plpg lookups for performance tests
            plpg_lookup_grid_distinct(h, dgh, return_grid_data, distinct)
          else
            ruby_lookup_grid_distinct(h, dgh, return_grid_data, distinct)
          end

  return vhash if vhash['result'].nil? || !dgh['data_type']

  c_data_type = Marty::DataGrid.convert_data_type(dgh['data_type'])

  return vhash if String === c_data_type

  res = vhash['result']

  v = if ::Marty::EnumHelper.pg_enum?(klass: res)
        c_data_type.find_by_name(res)
      elsif Marty::DataGrid == c_data_type
        follow ?
          Marty::DataGrid.lookup_h(pt, res) :
          Marty::DataGrid.lookup(pt, res)
      else
        Marty::DataConversion.find_row(c_data_type, { 'name' => res }, pt)
      end

  return vhash.merge('result' => v) unless
    Marty::DataGrid == c_data_type && follow

  visited ||= []

  visited << dgh['group_id']

  raise "#{self.class} recursion loop detected -- #{visited}" if
    visited.member?(v['group_id'])

  lookup_grid_distinct_entry_h(
    pt, h, v, visited, follow, return_grid_data, distinct)
end

.maybe_get_klass(type) ⇒ Object



659
660
661
662
663
# File 'app/models/marty/data_grid.rb', line 659

def self.maybe_get_klass(type)
    type.constantize unless INDEX_MAP[type] || type == 'float'
rescue NameError
    raise "unknown header type/klass: #{type}"
end

.null_value?(value, strict_null_mode) ⇒ Boolean

Returns:

  • (Boolean)


586
587
588
589
590
591
# File 'app/models/marty/data_grid.rb', line 586

def self.null_value?(value, strict_null_mode)
  return false unless value == NULL_STRING
  return true if strict_null_mode

  raise 'NULL is not supported in grids without strict_null_mode'
end

.parse(pt, grid_text, options) ⇒ Object

parse grid external representation into metadata/data



686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
# File 'app/models/marty/data_grid.rb', line 686

def self.parse(pt, grid_text, options)
  options[:headers] ||= false
  options[:col_sep] ||= "\t"

  pt ||= 'infinity'

  rows = CSV.new(grid_text, options).to_a
  blank_index = rows.find_index { |x| x.all?(&:nil?) }

  raise 'must have a blank row separating metadata' unless
    blank_index

  raise "can't import grid with trailing blank column" if
    rows.map { |r| r.last.nil? }.all?

  raise "last row can't be blank" if rows[-1].all?(&:nil?)

  data_type, lenient, strict_null_mode = nil, false, false

  # check if there's a data_type definition
  dt, constraint, *x = rows[0]
  if dt && x.all?(&:nil?)
    dts = dt.split

    lenient = dts.delete('lenient').present?
    strict_null_mode = dts.delete('strict_null_mode').present?
    data_type = dts.first
    raise "bad data type '#{dt}'" if dts.size > 1
  end

  constraint = nil if x.first.in?(['v', 'h'])

  start_md = constraint || data_type || lenient || strict_null_mode ? 1 : 0

   = rows[start_md...blank_index]
   = .map do |attr, type, dir, rs_keep, key|
    raise 'metadata elements must include attr/type/dir' unless
      attr && type && dir
    raise "bad dir #{dir}" unless ['h', 'v'].member? dir
    raise "unknown metadata type #{type}" unless
      Marty::DataGrid.type_to_index(type)

    keys = key && parse_keys(pt, [key], type, strict_null_mode)
    nots = key && parse_nots([key])
    wildcards = key && parse_wildcards([key])

    res = {
      'attr' => attr,
      'type' => type,
      'dir'  => dir,
      'keys' => keys,
      'nots' => nots,
      'wildcards' => wildcards,
    }
    res['rs_keep'] = rs_keep if rs_keep
    res
  end

  v_infos = .select { |inf| inf['dir'] == 'v' }
  h_infos = .select { |inf| inf['dir'] == 'h' }

  # keys+data start right after blank_index
  data_index = blank_index + 1

  # process horizontal key rows
  h_infos.each_with_index do |inf, i|
    row = rows[data_index + i]

    raise "horiz. key row #{data_index + i} must include nil starting cells" if
      row[0, v_infos.count].any?

    inf['keys'] = parse_keys(pt, row[v_infos.count, row.count], inf['type'], strict_null_mode)
    inf['nots'] = parse_nots(row[v_infos.count, row.count])
    inf['wildcards'] = parse_wildcards(row[v_infos.count, row.count])
  end

  raise 'horiz. info keys length mismatch!' unless
    h_infos.map { |inf| inf['keys'].length }.uniq.count <= 1

  data_rows = rows[data_index + h_infos.count, rows.count]

  # process vertical key columns
  v_key_cols = data_rows.map { |r| r[0, v_infos.count] }.transpose

  v_infos.each_with_index do |inf, i|
    inf['keys'] = parse_keys(pt, v_key_cols[i], inf['type'], strict_null_mode)
    inf['nots'] = parse_nots(v_key_cols[i])
    inf['wildcards'] = parse_wildcards(v_key_cols[i])
  end

  raise 'vert. info keys length mismatch!' unless
    v_infos.map { |inf| inf['keys'].length }.uniq.count <= 1

  c_data_type = Marty::DataGrid.convert_data_type(data_type)

  raise "bad data type #{data_type}" unless c_data_type

  # based on data type, decide to check using convert or instance
  # lookup.  FIXME: DRY.

  if String === c_data_type
    tsym = c_data_type.to_sym

    data = data_rows.map do |r|
      r[v_infos.count, r.count].map do |v|
        next v unless v

        Marty::DataConversion.convert(v, tsym)
      end
    end
  else
    data = data_rows.map do |r|
      r[v_infos.count, r.count].map do |v|
        next v unless v

        next v if Marty::DataGrid.
                       find_class_instance(pt, c_data_type, v)

        raise "can't find key '#{v}' for class #{data_type}"
      end
    end
  end

  {
    metadata: ,
    data: data,
    data_type: data_type,
    lenient: lenient,
    strict_null_mode: strict_null_mode,
    constraint: constraint,
  }
end

.parse_fvalue(pt, passed_val, type, klass, strict_null_mode = false) ⇒ Object



593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
# File 'app/models/marty/data_grid.rb', line 593

def self.parse_fvalue(pt, passed_val, type, klass, strict_null_mode = false)
  return unless passed_val

  v = remove_not(passed_val)

  return nil if null_value?(v, strict_null_mode)

  case type
  when 'numrange', 'int4range'
    Marty::Util.human_to_pg_range(v)
  when 'integer'
    v.split(ARRSEP).map do |val|
      next nil if null_value?(val, strict_null_mode)

      Integer(val) rescue raise "invalid integer: #{val}"
    end.uniq.sort_by(&:to_i)
  when 'float'
    v.split(ARRSEP).map do |val|
      next nil if null_value?(val, strict_null_mode)

      Float(val) rescue raise "invalid float: #{val}"
    end.uniq.sort
  when 'string'
    res = v.split(ARRSEP).uniq.sort.map do |val|
      next nil if null_value?(val, strict_null_mode)

      val
    end

    raise 'leading/trailing spaces in elements not allowed' if res.any? do |x|
      x != x&.strip
    end

    raise '0-length string not allowed' if res.any? do |x|
      x&.empty?
    end

    res
  when 'boolean'
    return nil if null_value?(v, strict_null_mode)

    case v.downcase
    when 'true', 't'
      true
    when 'false', 'f'
      false
    else
      raise "bad boolean #{v}"
    end
  else
    # AR class
    # FIXME: won't work if the obj identifier (name) has ARRSEP
    res = v.split(ARRSEP).uniq
    res.each do |k|
      begin
        # check to see if class instance actually exists
        Marty::DataGrid.
          find_class_instance(pt, klass, k) || raise(NoMethodError)
      rescue NoMethodError
        raise "instance #{k} of #{type} not found"
      end
    end
    res
  end
end

.parse_keys(pt, keys, type, strict_null_mode) ⇒ Object



665
666
667
668
669
670
671
# File 'app/models/marty/data_grid.rb', line 665

def self.parse_keys(pt, keys, type, strict_null_mode)
  klass = maybe_get_klass(type)

  keys.map do |v|
    parse_fvalue(pt, v, type, klass, strict_null_mode)
  end
end

.parse_nots(keys) ⇒ Object



673
674
675
676
677
678
679
# File 'app/models/marty/data_grid.rb', line 673

def self.parse_nots(keys)
  keys.map do |v|
    next false unless v

    v.starts_with?(NOT_STRING_START) && v.ends_with?(NOT_STRING_END)
  end
end

.parse_wildcards(keys) ⇒ Object



681
682
683
# File 'app/models/marty/data_grid.rb', line 681

def self.parse_wildcards(keys)
  keys.map(&:nil?)
end

.plpg_lookup_grid_distinct(h_passed, dgh, ret_grid_data = false, distinct = true) ⇒ Object



344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
# File 'app/models/marty/data_grid.rb', line 344

def self.plpg_lookup_grid_distinct(h_passed, dgh, ret_grid_data = false,
                                   distinct = true)
  cd = dgh['created_dt']
  @@dtcache ||= {}
  @@dtcache[cd] ||= cd.strftime(PLV_DT_FMT)
  row_info = {
    'id'         => dgh['id'],
    'group_id'   => dgh['group_id'],
    'created_dt' => @@dtcache[cd]
  }

  h = dgh['metadata'].each_with_object({}) do |m, h|
    attr = m['attr']
    inc = h_passed.fetch(attr, :__nf__)
    next if inc == :__nf__

    val = (defined? inc.name) ? inc.name : inc
    h[attr] = val.is_a?(String) ?
                ActiveRecord::Base.connection.quote(val)[1..-2] : val
  end

  fn     = 'lookup_grid_distinct'
  hjson  = "'#{h.to_json}'::JSONB"
  rijson = "'#{row_info.to_json}'::JSONB"
  params = "#{hjson}, #{rijson}, #{ret_grid_data}, #{distinct}"
  sql    = "SELECT #{fn}(#{params})"
  raw    = ActiveRecord::Base.connection.execute(sql)[0][fn]
  res    = JSON.parse(raw)

  if res['error']
    msg = res['error']
    parms, sqls, ress, dg = res['error_extra'].values_at(
      'params', 'sql', 'results', 'dg')

    raise "DG #{name}: Error in PLPG call: #{msg}\n"\
          "params: #{parms}\n"\
          "sqls: #{sqls}\n"\
          "results: #{ress}\n"\
          "dg: #{dg}\n"\
          "ri: #{row_info}" if res['error']
  end

  res
end

.register_rule_handler(handler) ⇒ Object



134
135
136
# File 'app/models/marty/data_grid.rb', line 134

def self.register_rule_handler(handler)
  (@@rule_handlers ||= []) << handler
end

.ruby_lookup_grid_distinct(h_passed, dgh, ret_grid_data = false, distinct = true) ⇒ Object



266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
# File 'app/models/marty/data_grid.rb', line 266

def self.ruby_lookup_grid_distinct(h_passed, dgh, ret_grid_data = false,
                                   distinct = true)

  grid = Marty::DataGrid.find(dgh['id'])
  indices = ruby_lookup_indices(h_passed, dgh)

  # We use the 0 as default, if there are no indices in that dir
  # Otherwise we find an intersection between all indices
  v_indices = if indices['v'].empty?
                [0]
              else
                indices['v'].reduce(:&)
              end

  h_indices = if indices['h'].empty?
                [0]
              else
                indices['h'].reduce(:&)
              end

  if distinct
    raise 'matches > 1' if v_indices.size > 1
    raise 'matches > 1' if h_indices.size > 1
  end

  v_index_min = v_indices.min
  h_index_min = h_indices.min

  if v_index_min.nil? || h_index_min.nil?
    nil_res = {
      'data' => nil,
      'name' => grid.name,
      'result' => nil,
      'metadata' => nil
    }

    return nil_res if grid.lenient && !ret_grid_data

    raise 'Data Grid lookup failed'
  end

  res2 = grid.data.dig(v_index_min, h_index_min)

  if ret_grid_data
    {
      'data' => grid.data,
       'name' => grid.name,
       'result' => res2,
       'metadata' => grid.
    }
  else
    {
      'data' => nil,
      'name' => grid.name,
      'result' => res2,
      'metadata' => nil
    }
  end
rescue StandardError => e
  ri = {
    'id' => grid.id,
    'group_id' => grid.group_id,
    'created_dt' => grid.created_dt
  }

  dg = grid.attributes.reject do |k, _|
    next true if !ret_grid_data && k == 'data'

    k == 'permissions'
  end

  raise "DG #{name}: Error in Ruby call: #{e.message} \n"\
    "params: #{h_passed}\n"\
    "results: #{[h_indices, v_indices]}\n"\
    "dg: #{grid.attributes}\n"\
    "ri: #{ri}"
end

.ruby_lookup_indices(h_passed, dgh) ⇒ Object



188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
# File 'app/models/marty/data_grid.rb', line 188

def self.ruby_lookup_indices(h_passed, dgh)
  dgh['metadata'].each_with_object({ 'v' => [], 'h' => [] }) do |m, h|
    attr = m['attr']

    inc = h_passed[attr]

    val = (defined? inc.name) ? inc.name : inc

    dir = m['dir']

    m_type = m['type']
    nots = m.fetch('nots', [])
    wildcards = m.fetch('wildcards', [])

    unless dgh['strict_null_mode']
      next unless h_passed.key?(attr)

      # FIXME: Treating passed nil in the same way
      # as missing broke our lookups. Maybe we should get back to it later.
      # Before missing attribute would match anything,
      # while explicitly passed nil would only match wildcard keys
      # We want to be consistent and treat nil attribute as missing one,
      # unless it's a stict_null_mode, where nil would be explicitly mapped
      # to NULL keys
      # next if val.nil?
    end

    converted_val = if val.nil?
                      nil
                    elsif m_type == 'string'
                      val.to_s
                    elsif m_type == 'integer'
                      val.to_i
                    elsif m_type == 'numrange'
                      val.to_f
                    elsif m_type == 'int4range'
                      val.to_i
                    elsif m_type == 'boolean'
                      ActiveModel::Type::Boolean.new.cast(val)
                    else
                      val
                    end

    arr = m['keys'].each_with_index.map do |key_val, index|
      wildcard = wildcards.fetch(index, true) # By default empty value is a wildcard

      next index if key_val.nil? && wildcard

      not_condition = nots[index]

      check_res = if ['int4range', 'numrange'].include?(m_type)
                    raise 'Data Grid lookup failed' if val.nil?

                    checks = Marty::Util.pg_range_to_ruby(key_val)
                    checks.all? do |check|
                      converted_val.send(check[0], check[1])
                    end
                  elsif key_val.nil?
                    val.nil?
                  elsif m_type == 'boolean'
                    key_val == converted_val
                  else
                    key_val.include?(converted_val)
                  end

      if check_res && !not_condition
        next index
      elsif !check_res && not_condition
        next index
      end

      nil
    end.compact

    h[dir] << arr
  end
end

.type_to_index(type) ⇒ Object



163
164
165
166
167
168
169
# File 'app/models/marty/data_grid.rb', line 163

def self.type_to_index(type)
  # map given header type to an index class -- uses string index
  # for ruby classes.
  return INDEX_MAP[type] if INDEX_MAP[type]

  INDEX_MAP['string'] if (type.constantize rescue nil)
end

Instance Method Details

#build_indexObject

FIXME: should be private



865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
# File 'app/models/marty/data_grid.rb', line 865

def build_index
  # create indices for the metadata
  .each do |inf|
    attr = inf['attr']
    type = inf['type']
    keys = inf['keys']
    nots = inf.fetch('nots', [])

    # find index class
    idx_class = Marty::DataGrid.type_to_index(type)

    keys.each_with_index do |k, index|
      gi              = idx_class.new
      gi.attr         = attr
      gi.key          = k
      gi.created_dt   = created_dt
      gi.data_grid_id = group_id
      gi.index        = index
      gi.not          = nots[index] || false
      gi.save!
    end
  end
end

#dir_infos(dir) ⇒ Object



480
481
482
# File 'app/models/marty/data_grid.rb', line 480

def dir_infos(dir)
  .select { |inf| inf['dir'] == dir }
end

#exportObject



568
569
570
571
572
573
574
575
576
577
578
579
# File 'app/models/marty/data_grid.rb', line 568

def export
   # return null string when called from Netzke on add_in_form
   return '' if .nil? && data.nil?

   meta_rows, h_key_rows, data_rows = export_array

   Marty::DataExporter.
     to_csv(meta_rows + [[]] + h_key_rows + data_rows,
            'col_sep' => "\t",
           ).
     gsub(/\"\"/, '') # remove "" to beautify output
end

#export=(text) ⇒ Object

FIXME: this is only here to appease Netzke add_in_form



531
532
# File 'app/models/marty/data_grid.rb', line 531

def export=(text)
end

#export_arrayObject



534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
# File 'app/models/marty/data_grid.rb', line 534

def export_array
  # add data type metadata row if not default
  lenstr = 'lenient' if lenient
  strict_null_mode_str = 'strict_null_mode' if strict_null_mode

  typestr = data_type unless [nil, DEFAULT_DATA_TYPE].member?(data_type)
  len_type = [lenstr, strict_null_mode_str, typestr].compact.join(' ')

  meta_rows = if len_type.present? || constraint.present?
                [[len_type, constraint].compact]
              else
                []
              end

  meta_rows += .map do |inf|
    [inf['attr'], inf['type'], inf['dir'], inf['rs_keep'] || '']
  end

  v_infos, h_infos = dir_infos('v'), dir_infos('h')

  h_key_rows = h_infos.map do |inf|
    [nil] * v_infos.count + self.class.export_keys(inf)
  end

  transposed_v_keys = v_infos.empty? ? [[]] :
    v_infos.map { |inf| self.class.export_keys(inf) }.transpose

  data_rows = transposed_v_keys.each_with_index.map do |keys, i|
    keys + (data[i] || [])
  end

  [meta_rows, h_key_rows, data_rows]
end

#freezeObject



127
128
129
130
131
132
# File 'app/models/marty/data_grid.rb', line 127

def freeze
  # FIXME: mcfly lookups freeze their results in order to protect
  # the cache.  That doesn't interact correctly with lazy_load which
  # modifies the attr hash at runtime.
  self
end

#saveObject

FIXME: hacky – save is just save!



159
160
161
# File 'app/models/marty/data_grid.rb', line 159

def save
  save!
end

#save!Object

FIXME: not sure what’s the right way to perform the save in a transaction – i.e. together with build_index. before_save would be OK, but then save inside it would cause an infinite loop.



145
146
147
148
149
150
151
152
153
154
155
156
# File 'app/models/marty/data_grid.rb', line 145

def save!
  if changed?
    transaction do
      nc, nw, n = [name_changed?, name_was, name]
      res = super
      update_rules(nw, n) if nc && nw.present?
      reload
      build_index
      res
    end
  end
end

#to_sObject



123
124
125
# File 'app/models/marty/data_grid.rb', line 123

def to_s
  name
end

#update_from_import(name, import_text, created_dt = nil) ⇒ Object



842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
# File 'app/models/marty/data_grid.rb', line 842

def update_from_import(name, import_text, created_dt = nil)
  parsed_result = self.class.parse(created_dt, import_text, {})

   = parsed_result[:metadata]
  data = parsed_result[:data]
  data_type = parsed_result[:data_type]
  lenient = parsed_result[:lenient]
  constraint = parsed_result[:constraint]
  strict_null_mode = parsed_result[:strict_null_mode]

  self.name             = name
  self.data             = data
  self.data_type        = data_type
  self.lenient          = !!lenient
  self.strict_null_mode = strict_null_mode
  # Otherwise changed will depend on order in hashes
  self.         =  unless  == 
  self.constraint       = constraint
  self.created_dt       = created_dt if created_dt
  save!
end

#update_rules(old, new) ⇒ Object



138
139
140
# File 'app/models/marty/data_grid.rb', line 138

def update_rules(old, new)
  @@rule_handlers.each { |rh| rh.call(old, new) }
end