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

Ruby on rails 从文件中获取模板字符串并自动绑定数据,ruby-on-rails,ruby,Ruby On Rails,Ruby,我正在实现SmsService以向用户的手机发送文本消息。SMS服务从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 itine

我正在实现SmsService以向用户的手机发送文本消息。SMS服务从
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
变量。如何重构此代码?具体来说,如何将消息模板存储在文件中并自动将数据绑定到模板?

首先在app/views/sms\u content/\u get\u content.html.erb下创建一个部分文件

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
\u get\u 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 %>

正如我在上面的评论中所指出的,Rails的内置功能实际上就是为这一点而设计的。首先,将模板字符串存储在
config/locales/
目录中:

#config/locales/en.yml
嗯:
sms_模板:
单程:
您好%{customer_name},这是您的单程行程
从%{出发地点}到%{到达地点}。。。
往返:
您好%{customer_name},这是您的往返行程
从%{出发地点}到%{到达地点}。。。
请注意,此格式使用
%{…}
a la
sprintf
进行插值,而不是
{…}

然后:


就这样!需要注意的一点是:上面假设
@data
是一个ActiveModel对象(或者用散列响应
属性的对象);如果不是这样的话,你必须先构建一个散列。

只需使用
render
方法。我是一个新的Ruby爱好者,所以如果你给出一个示例链接来呈现这个,那就太好了。请注意,现在的模板将能够执行任意Ruby代码。因此,你不应该从用户那里接受这些,否则用户可以在你的应用程序中执行任意代码(这会窃取密码、更改数据等)。如果你想为用户接受这些模板,你应该使用一种安全的模板语言,比如,为什么不使用Rails的I18NAPI,它基本上就是为这个目的而设计的呢@霍尔格只是我看不出这个漏洞。给我一个提示?
def get_content
   render :partial => "sms_content/get_content"
end
def get_content
  template_name = @sms_type == 1 ? "round_trip" : "one_way"
  I18n.t("sms_template.#{template_name}", @data.attributes)
end