我想完成这样的事情:
class Template
def initialize(temp_str)
# come code
end
def render options={}
# some code
end
end
template = Template.new("{{name}} likes {{animal_type}}")
template.render(name: "John", animal_type: "dogs")
# output: "John likes dogs"
template = Template.new("{{name}} likes {{animal_type}} and {{animal_type2}}")
template.render(name: "John", animal_type: "dogs", animal_type2: "cats")
# output: "John likes dogs and cats"
我应该如何编写代码..我不知道如何编写initialize
方法
答案 0 :(得分:1)
首先,这里我们不需要课程。 Singleton工作正常。
module Template
def render(name:, action: 'likes', **params)
puts "[DEBUG] parameters passed: #{params.keys.join(', ')}"
animals = params.values.join(' and ')
"#{name} #{action} #{animals}"
end
module_function :render
end
Template.render(name: 'John', animal_type: 'cats', animal_type2: 'dogs')
#⇒ [DEBUG] parameters passed: animal_type, animal_type2
# "John likes cats and dogs"
要从头开始重新制造一个可怜的车把,人们可能会这样做:
class Template
def initialize(template)
@template = template
end
def render(**params)
@template.gsub(/{{.*?}}/) { |m| params[m[/(?<={{).*(?=}})/].to_sym] }
end
end