开发者

Rails API - turning views into API responses

This has come up for me a couple times in the last week and I've been feeling like there must be some best practices or guidelines that I'm missing. We have a Rails app that we'd like to build an API for. We started by doing the standard thing:

...
respond_to :json

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

So elegant, but back to the real world...Our views in the main site have some amount of conditional logic for showing copy/messages that the consumers of the API want access to. It seems like a reasonable requirement, they don't want to hardcode the copy in the consuming (iPhone) application since they'll be releasing infrequently and we'd to be able to like to update the messaging on our cycle. Here's a made up example of some view code:

<% 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 %>

How are folks handling this sort of requirement?

1) I can add methods to the models that return the appropriate messaging for @post.profanity_m开发者_开发百科essage_text and :include those when we serialize the models for the API. However, in some cases there's a good amount of copy that really doesn't feel like it belongs in the model.

2) I can add a show.json.erb file that builds up the json response with all the messaging included, but that seems like it'll end up duplicating a good amount of code and feels relatively tedious.

Has anyone come across a pattern they're really happy with for this?

Thanks for the suggestions!


How about storing the messages to 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."

Usage with interpolations:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜