自己学習用のシンプルで小さなテンプレート パーサーを作成しようとしています。
「モジュール式」のものを構築してデータを共有するにはどうすればよいですか? データは外部からアクセスできる必要はありません。それは単なる内部データです。ここに私が持っているものがあります:
# 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
Phrogzのコメントに基づいて編集
私は現在、次のようなことを考えています:
p = TemplateParser.new(html, *args) # or TemplateParser::Base.new(html, *args)
p.append_css(file_or_string)
parsed_html = p.parse!
パーサーは非一般的な問題を解決する必要があり、移植性がないため、公開されたメソッドはあまりあるべきではありません。少なくともこの初期段階ではありません。私が試したことは、ノコギリから構造について少し覗くことです.