Class: SlimLint::Atom

Inherits:
Object
  • Object
show all
Defined in:
lib/slim_lint/atom.rb

Overview

Represents an atomic, childless, literal value within an S-expression.

This creates a light wrapper around literal values of S-expressions so we can make an Atom quack like a Sexp without being an Sexp.

Instance Method Summary collapse

Constructor Details

#initialize(value) ⇒ Atom

Creates an atom from the specified value.



10
11
12
# File 'lib/slim_lint/atom.rb', line 10

def initialize(value)
  @value = value
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method_sym, *args) { ... } ⇒ Object

Redirect methods to the value this SlimLint::Atom wraps.

Again, this is for convenience so we don’t need to manually unwrap the value ourselves. It’s pretty magical, but results in much DRYer code.

Yields:

  • block that was passed to the method



69
70
71
72
73
74
75
# File 'lib/slim_lint/atom.rb', line 69

def method_missing(method_sym, *args, &block)
  if @value.respond_to?(method_sym)
    @value.send(method_sym, *args, &block)
  else
    super
  end
end

Instance Method Details

#==(other) ⇒ Boolean

Returns whether this atom is equivalent to another object.

This defines a helper which unwraps the inner value of the atom to compare against a literal value, saving us having to do it ourselves everywhere else.



22
23
24
25
26
27
28
29
# File 'lib/slim_lint/atom.rb', line 22

def ==(other)
  case other
  when Atom
    @value == other.instance_variable_get(:@value)
  else
    @value == other
  end
end

#inspectString

Displays a string representation of this SlimLint::Atom suitable for debugging.



57
58
59
# File 'lib/slim_lint/atom.rb', line 57

def inspect
  "<#Atom #{@value.inspect}>"
end

#match?(pattern) ⇒ Boolean

Returns whether this atom matches the given Sexp pattern.

This exists solely to make an SlimLint::Atom quack like a Sexp, so we don’t have to manually check the type when doing comparisons elsewhere.



38
39
40
41
42
43
44
45
# File 'lib/slim_lint/atom.rb', line 38

def match?(pattern)
  # Delegate matching logic if we're comparing against a matcher
  if pattern.is_a?(SlimLint::Matcher::Base)
    return pattern.match?(@value)
  end

  @value == pattern
end

#respond_to?(method_sym, include_private = false) ⇒ Boolean

Return whether this SlimLint::Atom or the value it wraps responds to the given message.



83
84
85
86
87
88
89
# File 'lib/slim_lint/atom.rb', line 83

def respond_to?(method_sym, include_private = false)
  if super
    true
  else
    @value.respond_to?(method_sym, include_private)
  end
end

#to_sString

Displays the string representation the value this SlimLint::Atom wraps.



50
51
52
# File 'lib/slim_lint/atom.rb', line 50

def to_s
  @value.to_s
end