从文件中获取模板字符串并自动绑定数据

时间:2016-06-13 10:34:26

标签: ruby-on-rails ruby

我正在实施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个变量。我该如何重构这段代码?具体来说,如何将消息模板存储在文件中并自动将数据绑定到模板?

3 个答案:

答案 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的东西);如果不是这样,你将不得不先建立一个哈希。