Last active
August 29, 2015 14:00
-
-
Save tetsuyainfra/7976d723c42a0f56f31f to your computer and use it in GitHub Desktop.
ERB-TEMPLATEを便利に書くためのクラス
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# ERB-TEMPLATEを便利に書くためのクラス | |
# | |
# 使い方 | |
# module TEST_CONST | |
# extends TemplateGenerater | |
# TEST = "test_string-<%= id %>" | |
# end | |
# | |
# TEST_CONST::test(id: 1) #=> "test_string-1" | |
# TEST_CONST::test(id: 2) #=> "test_string-2" | |
# | |
# 使い方2 ネストしてもその先でインクルードしてね | |
# module TEST_CONST | |
# module INSIDE | |
# extends TemplateGenerater | |
# TEST = "test_string-<%= id %>" | |
# end | |
# end | |
# TEST_CONST::INSIDE::test(id: 1) #=> "test_string-1" | |
# | |
# 使い方3 もちろんClassでも使えるよ | |
# | |
# Class TestClass | |
# extends TemplateGenerater | |
# TEST = "test_string-<%= id %>" | |
# end | |
# TestClass::test(id: 1) #=> "test_string-1" | |
module TemplateGenerater | |
require 'erb' | |
require 'ostruct' | |
def method_missing(name, *args) | |
_name = ("TEMPLATE_" + name.upcase.to_s).to_sym | |
if constants.include? _name | |
return erb_conv( _name, args[0]) | |
else | |
super | |
end | |
end | |
def respond_to_missing?(method_name, include_private=false) | |
_name = ("TEMPLATE_" + method_name.to_s.upcase).to_sym | |
if constants.include? _name | |
true | |
else | |
super | |
end | |
end | |
private | |
def erb_conv(template_name, vars) | |
#puts "erb_conv call" | |
@erb_compiled = @erb_compiled || {} # extendsされたクラスでクラス変数を定義 | |
unless @erb_compiled.include? template_name | |
#puts "erb_conv:init" | |
@erb_compiled[template_name] = ERB.new( self.const_get template_name ) | |
end | |
@erb_compiled[template_name].result(OpenStruct.new(vars).instance_eval { binding } ) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
間違ってたら誰か教えて