1

I am new to rails . I started writing an application . My site has the same operation (here I need to create repository) , to be done via api and web UI .

so I created controller to do this . The method create will handle this .

Now I have the logic in the create function .

Now the same logic is what has to be used by the api two . No difference including the validation messages . So I should not repeat . or else the same logic will be at two places , which is wrong and makes life difficult .

Now there are a lot of ways to do this.

Method 1 :

-> get the common logic and push it inside a new method in the same controller (say create_service ) Then make the api path also routed to the same create method in controller and inside the controller from the path find if its an api call or web ui call .may be from the path say /a/b is a web call /api/a/b is a api call and the based on it make a decision whether to render the UI page or the json .

Method 2 : -> create a new ruby class with the business logic and make two controllers one for web ui and another for api and make both use the same ruby class . and so two url paths /a/b -> create in webuicontroller /api/a/b -> create in apicontroller

which is widely adopted and less confusing. I feel the method 2 is clean . what do you say ? . If both are wrong can you suggest a new way ?

If possible can someone also route me to a open source rails project where I can see these sorts of design ?

Harish Kayarohanam
  • 3,886
  • 4
  • 31
  • 55
  • 2
    [This](https://netguru.co/blog/service-objects-in-rails-will-help) might be an interesting article to read. It describes your method 2 in detail. – zwippie Nov 23 '14 at 12:46
  • 1
    There is a similar question http://stackoverflow.com/questions/24598265/is-it-necessary-to-build-a-separate-api-endpoint-for-mobile-apps-to-access-a-rai/24606030#24606030 – dre-hh Nov 23 '14 at 15:32

1 Answers1

0

Both are acceptable. As more your product grew as more you have different logic. For example: for web you will use Session authentication but for api you will use JWT. To be DRY(Don't repeat yourself) you can use shared logic. There are a lot of exceptions and you need to choose your own way.

Nosov Pavel
  • 1,571
  • 1
  • 18
  • 34