【发布时间】:2011-04-29 00:14:16
【问题描述】:
我如何重构这段代码,这样当它们使用相同的基本格式时,我就不会一遍又一遍地重复 json 对象?我对 Ruby on Rails 还是有点不适应,所以我不确定解决这个问题的最佳方法。
# PUT /users/:user_id/profile/:id
def update
if request.xhr?
profile = current_user.profile
if params[:profile].blank?
render :json => { :error => "There was no profile data passed in so your profile could not be saved." },
:status => :unprocessable_entity
else
if profile.update_attributes(params[:profile])
render :json => { :interests =>
simple_format(h(profile.interests), :class => "pbs tl"),
:favorite_music =>
simple_format(h(profile.favorite_music), :class => "pbs tl"),
:favorite_movies =>
simple_format(h(profile.favorite_movies), :class => "pbs tl"),
:favorite_books =>
simple_format(h(profile.favorite_books), :class => "pbs tl"),
:favorite_foods =>
simple_format(h(profile.favorite_foods), :class => "pbs tl") },
:status => :ok
else
render :json => { :error => get_errors_for_class(profile).to_sentence },
:status => :unprocessable_entity
end
end
end
end
更新:我稍微修改了原始答案,它对我有用。这是我的修改:
# within profile.rb
# create a hash of profile attributes
def html_to_hash
%w{interests favorite_music favorite_books favorite_foods}.inject({}) do |hash, property|
hash[property] = simple_format(h(self.send(property)), :class => 'pbs tl')
hash
end
end
【问题讨论】:
标签: ruby-on-rails json ruby-on-rails-3 refactoring dry