-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathgenerate_ai_classes
More file actions
executable file
·93 lines (78 loc) · 2.35 KB
/
generate_ai_classes
File metadata and controls
executable file
·93 lines (78 loc) · 2.35 KB
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#!/usr/bin/env ruby
require 'bundler/setup'
require 'gs1/syntax_dictionary/parser'
module GS1
# Generates AI classes based on the GS1 syntax dictionary.
#
# The input is the syntax dictionary located in the `gs1-syntax-dictionary.txt`
# file. The output is the `lib/gs1/generated_ai_classes.rb` file.
class AIClassesGenerator
def generate
data = File.read('gs1-syntax-dictionary.txt')
entry_data = GS1::SyntaxDictionary::Parser
.new(data)
.parse
.map { generate_single_entry(_1) }
.join("\n\n")
File.write('lib/gs1/generated_ai_classes.rb', template(entry_data))
end
private
module StringHelpers
refine String do
def blank? = empty? || /\A[[:space:]]*\z/.match?(self)
def indent(amount, indent_string: nil, indent_empty_lines: false)
indent_string = indent_string || self[/^[ \t]/] || ' '
re = indent_empty_lines ? /^/ : /^(?!$)/
gsub(re, indent_string * amount)
end
end
end
using StringHelpers
def template(entry_data)
<<~RUBY
# This file is generated by the `./bin/generate_ai_classes` script.
# Do not edit this file manually. See readme for more information.
module GS1
module GeneratedAIClasses
def self.ai_classes
#{entry_data}
end
end
end
RUBY
end
def generate_single_entry(entry)
allowed = format_allowed(entry)
separator = self.separator(entry)
name = self.name(entry)
format_entry <<~RUBY
Class.new(Record) do
define :length, allowed: #{allowed}
#{separator}
def self.name = '#{name}'
def self.ai = '#{entry.ai}'
def self.generated = true
end
RUBY
end
def format_entry(string)
string
.strip
.split("\n")
.reject(&:blank?)
.join("\n")
.indent(6)
end
def format_allowed(entry)
entry.length.count == 1 ? entry.length.begin.to_s : entry.length.to_s
end
def separator(entry)
entry.separator_required ? "define :separator\n" : ''
end
def name(entry)
name = entry.title.gsub(/[^\w]+/, '_')
name.match?(/^\d/) ? '_' + name : name
end
end
end
GS1::AIClassesGenerator.new.generate