我正在实施SmsService以向用户的手机发送短信。 SmsService从SmsContent
:
class SmsContent
def initialize(sms_type, data)
@sms_type = sms_type
@data = data
end
def get_content
sms_template_one_way = 'Hello #{customer_name}, this is your one way itinerary from #{depart_place} to #{arrive_place} ...'
sms_template_round_trip = 'Hello #{customer_name}, this is your round trip itinerary from #{depart_place} to #{arrive_place} ...'
customer_name = @data.customer_name
depart_place = @data.depart_place
arrive_place = @data.arrive_place
if @sms_type == 1
sms_content = sms_template_round_trip
else
sms_content = sms_template_one_way
end
sms_content
end
end
我必须将我的消息模板存储为String
个变量。我该如何重构这段代码?具体来说,如何将消息模板存储在文件中并自动将数据绑定到模板?
答案 0 :(得分:0)
class SmsContent
def initialize(sms_type, data); @sms_type, @data = sms_type, data end
def get_content
"Hello %{customer_name}, this is your %{sms_type} itinerary "\
"from %{depart_place} to %{arrive_place} ..." %
{
sms_type: @sms_type == 1 ? "round trip" : "one way",
customer_name: @data.customer_name,
depart_place: @data.depart_place,
arrive_place: @data.arrive_place,
}
end
end
答案 1 :(得分:0)
首先在app / views / sms_content / _get_content.html.erb下制作一个部分文件
<强> _get_content.html.erb 强>
<% if @sms_type == 1 %>
Hello <%= @data.customer_name %>, this is your one way itinerary from <%= @data.depart_place %> to <%= @data.arrive_place %> ...
<% else %>
Hello <%= @data.customer_name %>, this is your round trip itinerary from <%= @data.depart_place %> to <%= @data.arrive_place %> ...
<% end %>
在SmsContent
班级get_content
方法
def get_content
render :partial => "sms_content/get_content"
end
这应该有效
答案 2 :(得分:0)
正如我在上面的评论中指出的那样,Rails的内置I18n API实际上是针对这个问题而设计的。首先,将模板字符串存储在config/locales/
目录中:
# config/locales/en.yml
en:
sms_template:
one_way:
Hello %{customer_name}, this is your one way itinerary
from %{depart_place} to %{arrive_place} ...
round_trip:
Hello %{customer_name}, this is your round trip itinerary
from %{depart_place} to %{arrive_place} ...
请注意,此格式使用%{...}
a la sprintf
进行插值而不是#{...}
。
然后:
def get_content
template_name = @sms_type == 1 ? "round_trip" : "one_way"
I18n.t("sms_template.#{template_name}", @data.attributes)
end
就是这样!有一点需要注意:上面假设@data
是一个ActiveModel对象(或者用Hash响应attributes
的东西);如果不是这样,你将不得不先建立一个哈希。