简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM