Class: Confinicky::Parsers::Expression

Inherits:
Object
  • Object
show all
Defined in:
lib/confinicky/parsers/expression.rb

Overview

A simple class that parses a basic assignment expression

Constant Summary collapse

SINGLE_QUOTE_MATCHER =
/'([^']+)'/
DOUBLE_QUOTE_MATCHER =
/"([^"]+)"/

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(statement: nil) ⇒ Expression

Takes a line of code as a parameter and performs classification.



19
20
21
22
23
24
25
26
# File 'lib/confinicky/parsers/expression.rb', line 19

def initialize(statement: nil)
  @statement = statement.split("=")
  if valid?
    @name = @statement[0]
    @value = @statement[1]
    @value.gsub!("\n","") unless open?
  end
end

Instance Attribute Details

#nameObject (readonly)

The name of the variable being assigned. (LHS)



14
15
16
# File 'lib/confinicky/parsers/expression.rb', line 14

def name
  @name
end

Instance Method Details

#append_value(value) ⇒ Object

Appends additional string content to the value stored in the parser.



55
56
57
# File 'lib/confinicky/parsers/expression.rb', line 55

def append_value(value)
  @value += value
end

#open?Boolean

Determines if our statement is open ended. Meaning no closing quote for a provided opening quote.

Returns:

  • (Boolean)


62
63
64
# File 'lib/confinicky/parsers/expression.rb', line 62

def open?
  !@value.nil? && (uses_double_quotes? || uses_single_quotes?) && extracted_value.nil?
end

#uses_both_quotes?Boolean

Determines whether or not both types of quotes are present.

Returns:

  • (Boolean)


36
37
38
# File 'lib/confinicky/parsers/expression.rb', line 36

def uses_both_quotes?
  !(@value =~ /'/).nil? && !(@value =~ /"/).nil?
end

#uses_double_quotes?Boolean

Determines if the expression is wrapped in double quotes.

Returns:

  • (Boolean)


42
43
44
# File 'lib/confinicky/parsers/expression.rb', line 42

def uses_double_quotes?
  uses_both_quotes? && (@value =~ /'/) > (@value =~ /"/) || (@value =~ /"/) && (@value =~ /'/).nil?
end

#uses_single_quotes?Boolean

Determines if the expression is wrapped in single quotes.

Returns:

  • (Boolean)


48
49
50
# File 'lib/confinicky/parsers/expression.rb', line 48

def uses_single_quotes?
  !uses_double_quotes? && !(@value =~ /'/).nil?
end

#valid?Boolean

Ensures that the expression has an assigned value.

Returns:

  • (Boolean)


30
31
32
# File 'lib/confinicky/parsers/expression.rb', line 30

def valid?
  @statement.length == 2 && !@statement[1].nil?
end

#valueObject

The value which is being assigned to the variable in the expression (RHS)



68
69
70
71
72
73
# File 'lib/confinicky/parsers/expression.rb', line 68

def value
  quote = uses_double_quotes? ? "\"" : "\'"
  value = extracted_value
  value =  "#{quote}#{value}#{quote}" if !value.nil? && value =~ /\s/ && value != "\n"
  value
end