私は自己学習のための簡単な小さなテンプレートパーサーを構築しようとしています。サブモジュールとクラス間で変数を共有する
"モジュール式"を構築し、データを共有するにはどうすればよいですか?データは外部からアクセスする必要はなく、内部データだけです。ここで私が持っているものだ:パーサが解決しなければならないので、非常に公開されたメソッドがあるべきではありません
p = TemplateParser.new(html, *args) # or TemplateParser::Base.new(html, *args)
p.append_css(file_or_string)
parsed_html = p.parse!
:Phrogz」はコメント
に基づいて
# 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
ユーザーフレンドリーなコードに関する私の考えを加えました。 – pduersteler