开发者

globalize2 with xml/json support

开发者 https://www.devze.com 2022-12-17 10:42 出处:网络
I\'m implementing a distributed application, server with rails and mobile clients in objective c (iPhone). To enable internationalization, I use the rails plugin \'globalize2\' by joshmh.

I'm implementing a distributed application, server with rails and mobile clients in objective c (iPhone). To enable internationalization, I use the rails plugin 'globalize2' by joshmh.

However, it turned out that this plugin does not translate attributes when calling to_xml or to_json on an ActiveRecord. Does anyone know of a wo开发者_如何转开发rkaround / patch? Do you have any ideas how to fix this, where to alter globalize2?

Using: Rails 2.3.5 globalize2: commit from 2010-01-11


With Globalize2 (and with model_translations as well) translated attribute in a model is not a real attribute but is a method. Thus and so when you execute to_json method you can use :methods, as Joris suggested, but in a simpler way:

class Post < ActiveRecord::Base
  attr_accessible :title, :text
  translates :title, :text
end

class PostsController < ApplicationController
  def index   
    @posts = Post.all
    respond_to do |format|
        format.html
        format.json { render :json => { :posts => @posts.to_json(:only => :id, :methods => :title) }}
        format.js
    end
  end
end

Here I would like to receive only post id and title in json response. For additional information see to_json (Serialization) in Rails API.


I found this fork on github: http://github.com/leword/globalize2 But it looks like it is based on an older version.

I was looking for this myself, but solved my problem using the :methods option:

If you want to translate one attribute in @item, you can use:

class Item < ActiveRecord::Base
  translates :name
  def t_name
    self.name
  end
end

And in your controller:

render :text => @item.to_xml(:methods => [ :t_name ])

If your api path is something like /en/api/item.xml, you should get the english translation in the t_name attribute

For a belongs_to relation:

belongs_to :category
def category_name
  self.category.name
end

And in your controller:

render :text => @item.to_xml(:methods => [ :category_name ])

Your use case is probably different. Above is a workaround that works for me.

0

精彩评论

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