Variable exchange through submodules and classes

I am trying to create a simple little parser for self-learning.

How can I build something β€œmodular” and exchange data on it? Data should not be accessible from the outside, it is just internal data. Here is what I have:

# template_parser.rb
module TemplateParser
  attr_accessor :html
  attr_accessor :test_value

  class Base
    def initialize(html)
      @html = html
      @test_value = "foo"
    end

    def parse!
      @html.css('a').each do |node|
        ::TemplateParser::Tag:ATag.substitute! node
      end
    end
  end
end

# template_parser/tag/a_tag.rb
module TemplateParser
  module Tag
    class ATag
      def self.substitute!(node)
        # I want to access +test_value+ from +TemplateParser+
        node = @test_value # => nil
      end
    end
  end
end

Edit based on a comment by Phrogz
I am now thinking of something like:

p = TemplateParser.new(html, *args) # or TemplateParser::Base.new(html, *args)
p.append_css(file_or_string)
parsed_html = p.parse!

There should not be many open methods, because the parser must solve a non-general problem and cannot be tolerated. At least at this early stage. What I tried is a little look from Nokogiri about the structure.

+3
source share
1 answer

, , TemplateParser::Base parse!, :

# in TemplateParser::Base#parse!
::TemplateParser::Tag::ATag.substitute! node, self

# TemplateParser::Tag::ATag
def self.substitute!(node, obj)
  node = obj.test_value
end

attr_accessor Base, .

module TemplateParser
  class Base
    attr_accessor :html
    attr_accessor :test_value
    # ...
  end
end

, test_value, , , parse! - , .

, @test_value TemplateParser::Base. , , .

module TemplateParser
  class Base
    @test_value = "foo"
    class << self
      attr_accessor :test_value
    end
    # ...
  end
end

# OR

module TemplateParser
  @test_value = "foo"
  class << self
    attr_accessor :test_value
  end
  class Base
    # ...
  end
end

TemplateParser::Base.test_value OR TemplateParser.test_value .

, , , , , , , . , substitute! . node = test_value TemplateParser::Base#parse! . , , , , ...

+2

All Articles