メルマガ 没ねた
今朝ようやく
"mailAddress".sub(/(^.)/){|s| $1.upcase }
がシンプルな書き方であることに気がつく。
require 'erb' class String def upcase_head self.sub(/(^.)/){|s| $1.upcase } end end class JavaSourceModel attr_accessor :class_name def initialize() @properties = [] @methods = [] end def add_property property attr, type = property.gsub(/\s+/, "").split(":") @properties << [attr, type] end def each_property @properties.each { |attr, type| yield attr, type } end def add_method method @methods << method end def each_method @methods.each { |method| yield method } end end class JavaSourceGenerator def initialize(model) @model = model @erb = ERB.new(src) end def to_java @erb.result(binding) end def src <<-EOS // generate java source public class <%= @model.class_name %> { <% @model.each_property { | attr, type | %> private <%= type %> <%= attr %>; <% } %> <% @model.each_property do |attr, type | %> public <%= type %> get<%= attr.upcase_head %>() { return this.<%= attr %>; } public void set<%= attr.upcase_head %>(<%= type %> <%= attr %>) { this.<%= attr %> = <%= attr %>; } <% end %> <% @model.each_method do | method | %> <%= method %> <% end %> } EOS end end def main model = JavaSourceModel.new model.class_name = "Person" model.add_property "name:String" model.add_property "age : int" model.add_property "mailAddress : String " model.add_method <<-EOF public void sayHello() { System.out.println("hello! my name is " + getName()); } EOF generator = JavaSourceGenerator.new(model) puts generator.to_java end main __END__ run result $ ruby erb_sample.rb // generate java source public class Person { private String name; private int age; private String mailAddress; public String getName() { return this.name; } public void setName(String name) { this.name = name; } public int getAge() { return this.age; } public void setAge(int age) { this.age = age; } public String getMailAddress() { return this.mailAddress; } public void setMailAddress(String mailAddress) { this.mailAddress = mailAddress; } public void sayHello() { System.out.println("hello! my name is " + getName()); } }