Class: JSONCop::Analyzer

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

Constant Summary collapse

JSON_COP_ENABLED =
/jsoncop: enabled/
MODEL_NAME_REGEX =
/(struct|class)\s+(.+)\s*{/
ATTRIBUTE_REGEX =
/^\s+(let|var)\s(.+):(.+)/
JSON_TRANSFORMER_REGEX =
/^\s+static\s+func\s+(.+)JSONTransformer.+->.+/
JSON_BY_PROPERTY_HASH_REGEX =
/static\s+func\s+JSONKeyPathByPropertyKey\(\)\s*->\s*\[String\s*:\s*String\]\s*{\s*return\s*(\[[\s"a-z0-9A-Z_\-:\[\],]*)}/

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(file_path) ⇒ Analyzer

Returns a new instance of Analyzer.



17
18
19
# File 'lib/jsoncop/analyzer.rb', line 17

def initialize(file_path)
  @file_path = file_path
end

Instance Attribute Details

#file_pathObject (readonly)

Returns the value of attribute file_path.



14
15
16
# File 'lib/jsoncop/analyzer.rb', line 14

def file_path
  @file_path
end

#modelObject

Returns the value of attribute model.



15
16
17
# File 'lib/jsoncop/analyzer.rb', line 15

def model
  @model
end

Instance Method Details

#analyze!Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/jsoncop/analyzer.rb', line 21

def analyze!
  content = File.read file_path
  return unless content =~ JSON_COP_ENABLED
  content.each_line do |line|
    if line =~ MODEL_NAME_REGEX
      model_name = line.scan(MODEL_NAME_REGEX).flatten.last
      @model = Model::Model.new model_name
    elsif line =~ ATTRIBUTE_REGEX
      result = line.scan(ATTRIBUTE_REGEX).flatten
      @model.attributes << Model::Attribute.new(result[1], result[2])
    elsif line =~ JSON_TRANSFORMER_REGEX
      result = line.scan(JSON_TRANSFORMER_REGEX).flatten
      @model.transformers << result.first
    end
  end

  json_attr_list = content.scan(JSON_BY_PROPERTY_HASH_REGEX).flatten.first
  json_attr_list.gsub!(/[(\[\]"\s)]*/, '')
  @model.attr_json_hash = Hash[json_attr_list.split(",").map { |attr_json_pair| attr_json_pair.split(":").reverse }]
  @model
end