ruby on rails - Rabl Api and preventing code duplication -
i working on simple api rails project should able versioning. using rabl-rails gem.
to prevent code duplication, wanna able use controlleractions (ex. usercontroller#search) twice. 1 time normal webusers, , 1 api.
i saw people writing controllers this:
class api::v1::userscontroller def list @user = user.all end end
do have namespace controllers rabl? or possible "route or delegate" json requests existing controllers?
for example regular userscontroller
action "list" has this:
def list respond_to |format| format.html format.json { render @user } end end
views/users/list.json.rabl
exist , works in case.
now try move rabl files into
/api/v1/users/list.json.rabl
i provide route:
namespace :api, :defaults => {:format => :json} namespace :v1 match 'users/list', to: 'users#list', as: 'users', via: [:get, :post] end end
at moment not provide api::v1::userscontroller.
what best approach to
- provide /api/v1/users/list route but
- use regular userscontroller and
- have list.json.rabl view in /api/v1/ folder?
i hope it's not complicated explained...
i ended idea, api should have own logic. actions have view specific stuff (breadcrumbs, dropdown values, etc.) inside.
with knowledge "search logic" can extracted module gets mixed applicationcontroller class (inlcude). can use logic in both places: api , regular web view.
my first attempt here:
basecontroller
# base controller api requests class api::v1::basecontroller < applicationcontroller respond_to :json acts_as_token_authentication_handler_for user end
api subcontrollers
class api::v1::userscontroller < api::v1::basecontroller # inherit basecontroller -------^^^^^^^^^^^^^^^^^^^^^^^ # personal extracted logic include searchlogic def list @user = user.all end end
so
Comments
Post a Comment