2

I want to create a ruby on rails app, which provides an api and also a portal. Consider that we can create users and lets say todo entries via the api and the portal as well. To make it DRY I want to use the api methods, within the other controllers. So when the user creates a todo entry via the portal, the business logic of the corresponding api controller should be executed instead of copying the code from that controller to the todo controller. Also I do want a separate api controller, since other clients (like mobile phones) should call a certain endpoint (like %BASE_URI%/api/rest/v1/...) instead of the different controllers. Is that possible and are there any best practises?

Best regards dasheck

dasheck
  • 21
  • 2

1 Answers1

0

You can take your common code away, into helpers

module SomeHelper
    def your_method
        do_something
    end
end

class SomeController < ApplicationController
    include SomeHelper

    def method
       your_method 
    end
end

class AnotherController
    include SomeHelper

    def method
       your_method 
    end
end

Also You can use helper methods in any views without including

See documentation here and here

General Failure
  • 2,421
  • 4
  • 23
  • 49
  • So this means that I only have to add controller specific code to the actual controller (for api rendering the json and for the todo controller rendering the view respectively). Sounds reasonable for me. But doesn't that tend to produce duplicate wireframe code. The business logic would be in a central place tho, which is still a good thing. What I had in mind, was to use the router. So when the todo controller is called, it gets routed to the api and then back to the todo controller, where it can proceed the response from the api controller. Does that make sense? – dasheck Sep 24 '15 at 13:52
  • If You want use exactly controller methods,You can redirect to nessesary controller method, as in this [answer](http://stackoverflow.com/questions/5767222/rails-call-another-controller-action-from-a-controller) – General Failure Sep 24 '15 at 14:03
  • Thanks this helped me a lot. I will take a deeper look into it. – dasheck Sep 24 '15 at 15:31