Better way to write this piece of code

18 views
Skip to first unread message

Roy Royal

unread,
Feb 17, 2016, 5:53:11 PM2/17/16
to rubyonra...@googlegroups.com
I use this type of code for different message and status in my api.

def 404
respond_to do |format|
format.json {render json: { error: '404, not found' }, status: 404}
format.xml {render xml: { error: '404, not found' }, status: 404}
end
end

This works but can I refactoring this code, maybe to one single line?

--
Posted via http://www.ruby-forum.com/.

Tamara Temple

unread,
Feb 17, 2016, 11:34:59 PM2/17/16
to rubyonra...@googlegroups.com

Roy Royal <li...@ruby-forum.com> writes:

> I use this type of code for different message and status in my api.
>
> def 404
> respond_to do |format|
> format.json {render json: { error: '404, not found' }, status: 404}
> format.xml {render xml: { error: '404, not found' }, status: 404}
> end
> end
>
> This works but can I refactoring this code, maybe to one single line?

While I can applaud the desire, I think in this case you should NOT
attempt to simplify that in any way, as it would obfuscate what's going
on. This is clean, terse, and extremely clear what is going on.

If this sort of thing is repeated over and over with different status
codes, *that* should be simplified into a single method, passing in the
code.

--
Tamara Temple
tam...@gmail.com
http://www.tamouse.org

Roy Royal

unread,
Feb 18, 2016, 6:37:13 PM2/18/16
to rubyonra...@googlegroups.com
> While I can applaud the desire, I think in this case you should NOT
> attempt to simplify that in any way, as it would obfuscate what's going
> on. This is clean, terse, and extremely clear what is going on.
>
> If this sort of thing is repeated over and over with different status
> codes, *that* should be simplified into a single method, passing in the
> code.

Thanks Tamara you made me realize that short syntax is not always best.
Reply all
Reply to author
Forward
0 new messages