Class: ToFactory::Parsing::Syntax

Inherits:
Object
  • Object
show all
Includes:
RubyParsingHelpers
Defined in:
lib/to_factory/parsing/syntax.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from RubyParsingHelpers

#ruby2ruby, #ruby_parser, #to_ruby

Constructor Details

#initialize(contents) ⇒ Syntax

Returns a new instance of Syntax.



17
18
19
# File 'lib/to_factory/parsing/syntax.rb', line 17

def initialize(contents)
  @contents = contents
end

Instance Attribute Details

#contentsObject

Returns the value of attribute contents.



15
16
17
# File 'lib/to_factory/parsing/syntax.rb', line 15

def contents
  @contents
end

Instance Method Details

#factoriesObject



43
44
45
46
47
48
49
# File 'lib/to_factory/parsing/syntax.rb', line 43

def factories
  if multiple_factories?
    factories_sexp[1..-1]
  else
    [factories_sexp]
  end
end

#factories_sexpObject



51
52
53
# File 'lib/to_factory/parsing/syntax.rb', line 51

def factories_sexp
  header? ?  sexp[3] : sexp
end

#header?Boolean

Returns:

  • (Boolean)


61
62
63
# File 'lib/to_factory/parsing/syntax.rb', line 61

def header?
  sexp[1][1][1] == :FactoryGirl rescue false
end

#multiple_factories?Boolean

Returns:

  • (Boolean)


21
22
23
# File 'lib/to_factory/parsing/syntax.rb', line 21

def multiple_factories?
  factories_sexp[0] == :block
end

#name_from(sexp) ⇒ Object



55
56
57
58
59
# File 'lib/to_factory/parsing/syntax.rb', line 55

def name_from(sexp)
  sexp[1][3][1]
rescue NoMethodError
  raise CouldNotInferClassException.new(sexp)
end

#parent_from(x) ⇒ Object



65
66
67
68
69
70
71
72
73
# File 'lib/to_factory/parsing/syntax.rb', line 65

def parent_from(x)
  # e.g.
  #s(:call, nil, :factory, s(:lit, :admin), s(:hash, s(:lit, :parent), s(:lit, :"to_factory/user")))
  x[1][4][2][1]
rescue  NoMethodError
  # e.g.
  #s(:call, nil, :factory, s(:lit, :"to_factory/user"))
  x[1][3][1]
end

#parseObject



25
26
27
28
29
30
31
32
# File 'lib/to_factory/parsing/syntax.rb', line 25

def parse
  factories.map do |x|
    representation_from(x)
  end

rescue Racc::ParseError, StringScanner::Error => e
  raise ParseException.new("Original exception: #{e.message}\n #{e.backtrace.join("\n")}\nToFactory Error parsing \n#{@contents}\n o")
end

#representation_from(x) ⇒ Object



35
36
37
38
39
40
41
# File 'lib/to_factory/parsing/syntax.rb', line 35

def representation_from(x)
  Representation.new(name_from(x), parent_from(x), to_ruby(x))
rescue CouldNotInferClassException => e
  ruby = to_ruby(e.sexp)
  Kernel.warn "ToFactory could not parse\n#{ruby}"
  NullRepresentation.new(e.sexp)
end