ruby...

Post on 14-Feb-2017

47 Views

Category:

Technology

2 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Ruby メタプログラミングによるXML テンプレートエンジンの実装と評価Ryota Suzuki

自己紹介Ruby on Rails

酒温泉音楽

動機

サンプルコード doctype

html do

head do

meta "http-equiv" => "Content-type", content: %w(text/html; charset=utf-8)

title do

"XMLRサンプルファイル "

end

end

body do

div class: %w(wrapper content-main) do

"XMLRへようこそ "

end

end

end

get

実装方針

Module#method_missing def method_missing(method_name, *args, &block)

if block_given?

content_tag(method_name, *args, block)

else

empty_tag(method_name, *args)

end

end

未定義のメソッドをタグへ def content_tag(name, *args, block)

add_content "<#{name}#{args_to_param(*args)}>\n"

@@nest_level += 1

add_content "#{block.call}\n"

@@nest_level -= 1

add_content "</#{name}>\n"

""

end

% 記法def args_to_param(*args) # 中略 " " + args[0].inject("") do |base, kv|

%(#{base} #{kv[0]}="#{value_to_str(kv[1])}")

end[1..-1]

end

二重評価問題def add_content(str)

@@content += str

end

# => 戻り値 : str 自体 + @@content に格納# ここで 1ヶ月ほど開発がストップ…

Object#tap

def add_content(str)

str.tap do |text|

@@content += indent + text

end

end

Module.included

def self.included(base)

@@content = ""

@@nest_level = 0

end

先行事例との比較

実験変数評価場合分け(case...when)

ループ (each)

比較対象ERB Slim

HTML 出力用コード- XMLR ( 当 ) ERB Slim

行数 25 21 14

文字数 335 340 210

※require, include, get( 後述 ), nil( 後述 ) が必要なため行数が増大したと考察

実装行数- XMLR ( 当 ) Slim

行数 74 2101

※ $ wc -l `find lib/ -type f` の実行結果

シンタックスXMLR ( 当 ) ERB Slim

Ruby 専用 専用

課題と展望

実装上の難点get メソッド

クラス変数の評価、リセットeach → nil が必須each した変数が組み込まれてしまう

エラーが出た時恐ろしく分かりにくい

今後の課題Kernel メソッド、予約語との競合 (`p` など )Ruby メソッド名でない記号 (`-` など )

専用のメソッドを定義可能class="", id="" が冗長 (vs. Slim)

専用構文で対応可能

結論

Slim すごいBuilder gem との比較は時間が

参考Twitter: pocke

https://twitter.com/p_ck_/status/807392401908068352

Slim template

https://github.com/slim-template/slim

http://slim-lang.com

Builder

https://github.com/jimweirich/builder

メタプログラミング Ruby

https://www.oreilly.co.jp/books/9784873117430/

Thanks for listening.

top related