Rails API - 将视图转换为API响应

时间:2011-01-16 18:06:37

标签: ruby-on-rails api ruby-on-rails-3 rest

在过去的一周里,我已经多次出现这种情况,我一直觉得必须有一些我缺少的最佳实践或指导方针。我们有一个Rails应用程序,我们想为其构建一个API。我们从标准的事情开始:

...
respond_to :json

def show
  @post = Post.find(params[:id])
  respond_with @post
end
...

如此优雅,但回到现实世界......我们在主站点中的视图具有一些条件逻辑,用于显示API的消费者希望访问的副本/消息。这似乎是一个合理的要求,他们不想硬编码副本消费(iPhone)的应用,因为他们会经常释放,我们倒是要能想更新我们的周期消息。以下是一些视图代码的组成示例:

<% if @post.profanity_detected? %>
  This post is under review and it'll go live within <%= @post.review_period %> days. Blah blah additional copy...
<% else %>
  Your post for <%= @post.title %> looks great...
<% end %>

人们如何处理这种要求?

1)我可以为返回@ post.profanity_message_text的相应消息传递的模型添加方法,并且:在我们为API序列化模型时包含这些方法。但是,在某些情况下,有大量的副本确实不像它属于模型。

2)I可以添加建立起与包括所有消息传递JSON响应一个show.json.erb文件,但是,似乎是它会最终复制的代码量好,感觉比较繁琐。

有没有人遇到他们真的很满意的模式?

感谢您的建议!

1 个答案:

答案 0 :(得分:1)

如何将邮件存储到config/locale/en.yml

en:
  post:
    accepted: "Your post for %{title} looks great..."
    reviewed: "This post is under review and it'll go live within %{review_period} days."

使用interpolations

I18n.t "post.accepted", :title => @post.title
I18n.t "post.reviewed", :review_period => @post.review_period