how can refactor code don't repeat json objects on , on again when use same basic format? i'm still bit uncomfortable ruby on rails i'm unsure of best way approach this.
# put /users/:user_id/profile/:id def update if request.xhr? profile = current_user.profile if params[:profile].blank? render :json => { :error => "there no profile data passed in profile not 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
update: modified original answer little , works me. here's modification:
# within profile.rb # create hash of profile attributes def html_to_hash %w{interests favorite_music favorite_books favorite_foods}.inject({}) |hash, property| hash[property] = simple_format(h(self.send(property)), :class => 'pbs tl') hash end end
make data in huge hash method of profile
.
class profile def to_hash [:interests, :favorite_music, :favorite_books, :favorite_foods].inject({}) |h, prop| h[prop] = simple_format(h(self.send(:prop)), :class => 'pbs tl') h end end end
then
# put /users/:user_id/profile/:id def update if request.xhr? profile = current_user.profile if params[:profile].blank? render :json => { :error => "there no profile data passed in profile not saved." }, :status => :unprocessable_entity else if profile.update_attributes(params[:profile]) render :json => profile.to_hash, :status => :ok else render :json => { :error => get_errors_for_class(profile).to_sentence }, :status => :unprocessable_entity end end end end
Comments
Post a Comment