Class: Phlexing::NameSuggestor

Inherits:
Object
  • Object
show all
Defined in:
lib/phlexing/name_suggestor.rb

Class Method Summary collapse

Class Method Details

.call(source) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/phlexing/name_suggestor.rb', line 7

def self.call(source)
  document = Parser.call(source)
  analyzer = RubyAnalyzer.call(source)

  ivars  = analyzer.ivars
  locals = analyzer.locals

  ids     = extract(document, :extract_id_from_element)
  classes = extract(document, :extract_class_from_element)
  tags    = extract(document, :extract_tag_name_from_element)

  return wrap(ivars.first) if ivars.one? && locals.none?
  return wrap(locals.first) if locals.one? && ivars.none?
  return wrap(ids.first) if ids.any?
  return wrap(ivars.first) if ivars.any?
  return wrap(locals.first) if locals.any?
  return wrap(classes.first) if classes.any?
  return wrap(tags.first) if tags.any?

  "Component"
end

.extract(document, method) ⇒ Object



33
34
35
36
37
# File 'lib/phlexing/name_suggestor.rb', line 33

def self.extract(document, method)
  return [] unless document

  document.children.map { |element| send(method, element) }.compact
end

.extract_class_from_element(element) ⇒ Object



52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/phlexing/name_suggestor.rb', line 52

def self.extract_class_from_element(element)
  return if element.nil?
  return if element.is_a?(Nokogiri::XML::Text)

  class_attribute = element.attributes && element.attributes["class"]

  return if class_attribute.nil?

  classes = class_attribute.value.strip.split

  return if classes.empty?

  classes[0]
end

.extract_id_from_element(element) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/phlexing/name_suggestor.rb', line 39

def self.extract_id_from_element(element)
  return if element.nil?
  return if element.is_a?(Nokogiri::XML::Text)

  id_attribute = element.attributes && element.attributes["id"]
  return if id_attribute.nil?

  id = id_attribute.value.to_s.strip
  return if id.include?("<erb")

  id
end

.extract_tag_name_from_element(element) ⇒ Object



67
68
69
70
71
72
73
74
# File 'lib/phlexing/name_suggestor.rb', line 67

def self.extract_tag_name_from_element(element)
  return if element.nil?
  return if element.is_a?(Nokogiri::XML::Text)

  return if ["div", "span", "p", "erb"].include?(element.name)

  element.name
end

.wrap(name) ⇒ Object



29
30
31
# File 'lib/phlexing/name_suggestor.rb', line 29

def self.wrap(name)
  "#{name}_component".underscore.camelize
end