Skip to content

Instantly share code, notes, and snippets.

@tetsuyainfra
Last active August 29, 2015 14:00
Show Gist options
  • Save tetsuyainfra/7976d723c42a0f56f31f to your computer and use it in GitHub Desktop.
Save tetsuyainfra/7976d723c42a0f56f31f to your computer and use it in GitHub Desktop.
ERB-TEMPLATEを便利に書くためのクラス
# 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
@tetsuyainfra
Copy link
Author

間違ってたら誰か教えて

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment