Call a controller's method from an external ruby script - ruby

I'm creating an external service of my rails app. This is always listening a rabbitmq queue and all their messages should be redirected to some methods of the rails controllers.
I've tried these approaches:
AMQP subscriber inside Rails app
What's the correct way to run one controller action from another controller action without an HTTP redirect?
http://www.misuse.org/science/2007/07/24/firing-rails-controller-actions-from-command-line-console/
The first one allowed me only to access the model (Anyway I suppose must be the base for what I want). The second one... never worked for me. And the last one doesn't works on rails 3 ( ActionController::Integration doesn't exists)
I think that the last approach still could be used if I figure out how the sessions are handled in rails 3. In any case, somebody had tried something similar before? Any suggestion will be appreciated.

Why not just send the request via an HTTP request? Your controller basically makes actions visible via URLs - simply making a request to the URL is essentially the same as calling the controller code, and it keeps your code working like a software service/API. You could even just use curl to do this if you want.
Otherwise, if the two files are in the same machine/folder, you could try to explicitly include the one controller code in the other, but that seems like maybe not the way to go. Depends on how you want the end result to work.

Related

Where to put ajax request in Ember tutorial app?

I want to add "Weather: 24C" to the rental-listing component of the super-rentals tutorial app.
Where would be the "best-practices" place to put this ajax request?
Ember.$.getJSON(`http://api.openweathermap.org/data/2.5/weather?q=${location}&APPID=${apiKey}`)
.then(function(json) {
return JSON.parse(json).main.temp;
});
Do I need to add a component, add a model, add a service, add a second adapter, modify the existing adapter? Something else? All of these? Is the problem that the tutorial uses Mirage? I ask this because when I think I'm getting close, I get an error like this:
Mirage: Your Ember app tried to GET
'http://api.openweathermap.org/data/2.5/weather?q=london&APPID=5432',
but there was no route defined to handle this request.
Define a route that matches this path in your
mirage/config.js file. Did you forget to add your namespace?
You need to configure mirage to allow you making calls to outside in case mirage is active; what I mean is using this.passthrough function within mirage/config.js, that is explained in api documentation quite well.
Regarding your question about where to make the remote call is; it depends:
If you need the data from the server to arrive in case a route is about to open; you should prefer putting it within model hook of the corresponding route.
If you intend to develop a component that is to be reused from within different routes or even from within different applications with the same remote call over and over again; you can consider putting the ajax remote call to a component. Even if that is not a very common case usually; it might be the case that a component itself should be wrapped up to fetch the data and display it by itself for reusing in different places; there is nothing that prevents you to do so. However by usually applying data-down action-up principle; generally the remote calls fall into routes or controllers.
Whether using an ember-data model is another thing to consider. If you intend to use ember-data; you should not directly use Ember.$.ajax but rather be using store provided by ember-data and perhaps providing your custom adapter/serializer to convert data to the format ember-data accepts in case the server do not match to the formats that ember-data accepts. In summary; you do not need to use models if you use pure ajax as you do in this question.

How to organize my code?

I'm still in a learning phase with PHP and Laravel 5 and since I upgraded to L5, I struggle with where my code belongs to. There are so many files and folders which seem to have the same purpose or at least are very similar. There are Commands, Controllers, Events, Services, Requests, etc. I give an example with my workflow and where I would place the code and I hope you guys can comment on that and correct/help me.
Situation
I want to register a new user in my application and send a welcome e-mail when he registered successfully.
Workflow
Controller (UserController): Returns requested view (register).
Request (RegisterRequest): The "RegisterRequest" validates the entered data.
Controller (UserController): Passes the validated data to the "UserRegistrar" (service) in 'App/Services'.
Service (UserRegistrar): Creates a new user and saves it to the database.
Controller (UserController): Fires the "UserWasRegistered" Event.
Event (UserWasRegistered): This Event call the "SendWelcomeEmail" Command.
Command (SendWelcomeEmail): This Command will send/queue the welcome e-mail.
Controller (UserController): Redirects the user to a view with the information that he has been registerd successfully and a message has been send to him.
Logic
Okay, let's discuss some logic:
Controller:
Doesn't hold much code.
Mainly there to return views (with requested data).
Handles workflow and "connects" modules (Services, Requests, Events).
Request: Validates the data for a specified request
Service: A service "does" something. For example it's doing requests to the database.
Event: An Event is a central place to call one or more tasks if it is fired (SendConfirmationMail, SendWelcomeMail).
Command: Mainly there to handle the logic for ONE certain task. For example sending a confirmation mail. Another command will hold the logic for sending the welcome mail. Both commands are called in the Event described before.
Repositories: What is that?!
So this is what I understand. Please help me and feed me with information.
Thanks,
LuMa
Your question is a little vague and will likely attract downvotes as being "too broad". That said, here's my take on this...
The biggest issue I see is that your application structure is very different from the recommended L5 structure - or even the standard MVC structure - that it's no wonder you're getting confused.
Let's talk about your "Logic" section:
controller - you're on the right track here. The controller is the glue between your models and your views. It can do some processing, but most should be offloaded to classes that handle specific tasks.
request - what is this? L5 includes a Request class that includes methods for examining the HTTP request received from the client. Are you talking about subclassing that? Why? If your idea of a "request" class is primarily concerned with examining input, you can either do that in your model (ie. validating stuff before sticking it in the database) or in your controller (see the L5 docs on controller validation)
service - again, what is this? You talk about "doing requests to the database", but L5 provides a class for that (DB). At a higher level, database access should primarily be done through models, which abstract away most of the low level database access. As for other services, what I usually do is create libraries to perform specific processing. For example, my application has a particular third party project management application that it accesses via an API. I have a library for that, with methods such as getProject or createProject.
event - An event is a way of ensuring that some code is called when the event happens, without a whole lot of messing about. It sounds like you have the right idea about events.
command - again, it sounds like you have the basic idea about commands.
repositories - these are way of abstracting the connection between a resource (primarily the database, but it can apply to other resources too) and the code that uses the resource. This gives a way to switch the underlying resource more easily if you (for example) decide to change database servers in the future. They are optional.
You also haven't mentioned anything about models. L5 provides an excellent way to deal with your data in understandable chunks via Eloquent models - this will make your life much easier.
My suggestion is this: start small. Build a simple MVC application with L5 - A model (to save some data), a view (to display the data), and a controller (to put the model & view together by handling the client request). Once you have that, start extending it.
There are tutorials out there that will give you this basic structure for Laravel - most are for Laravel 4, but see if you can follow the basic ideas and build something similar for Laravel 5.

Easy way for no-content without controller

I am using Spring Security with Spring Controllers. There are some weird requests caused by some third party browser extension ending such as undefined or weird hexadecimal numbers. I would like to configure my application to block these requests but I could not find an easy way.
I do not want to declare a empty controller for this purpose. What is the correct way to return no-content for these requests?
Edit:
Some sample requets:
/activity/favorites/undefined
/activity/favorites/my/undefined
/help/undefined
Create some servlet filter that is invoked for every request (*). That filter has to check the request URL, and if it is on of the "strangers" that return what you want, but prevent the request from being future processed.

dynamic routing in sinatra based on request domain

Lets say I have a modular Sinatra app being used for a hundred sites, that I need to conditionally pull in routes for - if the request.host is example.com then I want to register the routes in file example_routes.rb - but if the request.host is say, other_example.com, then I want to register another set of routes completely, ignoring the first file completely.
One could also argue the app is trying to do too many things, but for the sake of this discussion, I'd love to hear some ideas and approaches.
Unfortunately, it appears that by the time the request object comes through (which is needed to register the new routes), that routes can no longer be registered. This is the nature of my problem.
As you’ve noticed, you can’t define routes based on a request since they are all setup at startup before the first request comes in.
One way to achieve what you’re after could be to make use of the :host_name condition:
get 'a_route', :host_name => 'example.com' do
# this route will only apply to requests to example.com
end
get 'a_route', :host_name => 'other_example.com' do
# this route will only apply to requests to other_example.com
end
These can be in different files if you want, and they won’t override each other so you can call them both at startup and requests will be routed to the appropriate code. Development and testing may be tricky, you may need to work out some way of accessing all routes locally.

Access request parameters from a JSP View in Spring Web MVC without putting them in a model

I'd like to be able to access some HTTP GET parameters directly in a JSP, without having to pass them through a Controller+Model, but at the same time still use the dispatcher/controller/model/view mechanism for other parameters and logic.
This is because I have many HTTP GET parameters that are generated by Javascript and used also only in Javascript. My Controllers don't need them at all.
I tried ${arg}, ${request.arg}, ${requestScope.arg}, nothing seems to work.
If I bypass the dispatcher, ${requestScope.arg} works.
But is there a way to make it work with the dispatcher?
Thanks!
If that's request parameters that you want to access (and not request attributes like the title says), then the syntax is ${param.parameterName}.
If it's request attributes, then it's ${requestScope.attributeName}.
See http://java.sun.com/products/jsp/syntax/2.0/syntaxref207.html#1010522 for a quick reference.

Resources