In Rails 4, how does one execute an arbitrary controller action and render the response to a string?
This is obviously a bad practice, but there are circumstances when it becomes very difficult to avoid:
You are making an offline copy or e-mail attachment of a dynamically rendered pdf (or any self-contained response).
Aforementioned response involves views and controllers not under your control, or in external gems.
Aforementioned views involve layouts and dozens of partials using relative paths and custom template rendering engines.
In some circumstances (when calling from another controller), it is possible to eliminate the dependency on the controller by replacing any data needed by the view. However, this typically still breaks the view rendering, as relative paths can no longer be passed to the render function within partials (among other issues).
So I haven't actually done this. Or anything like it.
But I remembered you can get a Rack app object for any arbitrary rails action. So it seemed like you could use that rack-compat interface to all an arbitrary action and get a response internally, without actually having to make an http request.
Googled around things I vaguely remembered to put the pieces together, and got this, which I have tried out in a very simple dummy app I made, and it seems to work:
rack_env = Rack::MockRequest.env_for("/some/url?foo=bar")
rack_app = SomeController.action(:index)
(status, headers, rack_body) = rack_app.call(rack_env)
str = rack_body.body
I was surprised to need to call #body on the thing I already thought was the body, not sure exactly what's going on I guess I don't entirely understand the rack api. Not sure if MockRequest is the right way to build a request. Not sure if there's a better way (but heck 3-4 lines ain't bad). But it does seem to work.
(There's probably a way to get the 'right' way to work too, with enough work -- there are for instance ways to change or add to the view template lookup paths, to put the original controller's views on the view lookup path, even when you're rendering the template from a new view. But I believe you that it gets painful, and am honestly not sure in this case what the 'right' way to do it is, I think the Rack method seems reasonable)
Related
I'm learning how to do routing in MVC. It seems to me that the routing API only solves half the problem. I can easily see how to map incoming URLs to controller actions and params. However, it is not obvious to me how to generate these routed URLs in the source code of my pages.
For example, in one of my views, I use this code to get the route URL:
<a class="listingResult" href="#Url.RouteUrl("ListingSEO", new { id = Model.Listing.ID, seoName = ListingController.SeoName(Model.Listing.Title) })">
This seems like poor coding practice to me for several reasons:
If the route changes in the future, I may have many places in my View code that will need updating.
The View now requires knowledge of the ListingController (maybe this is not a big deal?)
I've lost strong typing on my input params, and if I misspell the param names, my code is broken, but this doesn't generate compile warnings.
How do I observe good coding standards when I am generating route URLs? The alternative seems to be putting static functions in the controller to generate routes, which would at least address concerns #1 and #3. If I worked with you and you saw the code above, how unhappy would you be?
My recommendations:
Generate URLs in the ViewModel, not the View: This will keep your views cleaner and logic free. You can pass the UrlHelper instance from the controller to the ViewModel, which will also help for my next point...
Use a strongly-typed URL generation technique: Such as delegate-based, expression-based or code generation.
One of the purposes of using named routes is to abstract the controller/action. Your named routes shouldn't really change. At the most, you'd just change the controller/action they hit, but that happens seamlessly behind the scenes because you're using named routes.
Your view requires knowledge of the controller because you've added a dependency on it. This is bad for a number of reasons. There's many different ways you could handle this that wouldn't require a dependency on the controller, depending on what it is you're actually doing here, but at the very least, you should simply use a utility class, so at least it wouldn't be controller-specific.
The route params are intentionally not strongly-typed, because routes are flexible by design. You can pass anything you want to the action, with or without a parameter to catch it (you can use something like Request to get at it without a param).
According to ruby docs, the translate (or t) helper delegates to I18n#translate but also performs several additional functions, among which is: "it’ll mark the translation as safe HTML if the key has the suffix _html".
I would expect that it should work equally in both views and in controllers, but in my experience it doesn't: t(:hello_html) does work as expected in views (marks the translation as html_safe), but it does not mark the result as safe html when invoked from a controller.
To reproduce the problem you could add hello_html: '<i>Hello world</i>' to your locales/en.yml and flash.now[:notice] = t(:hello_html) to any convenient action of any controller. For me that resulted in an escaped html markup in a flash messages area which was an unexpected outcome for me.
My questions are:
is there anyone else who experienced or is able to reproduce this problem?
what is it: a rails bug, a feature, or just my project's unique "oddity"?
is there any easy way to work this around?
(Tested in rails 3.2.11 and 3.2.13)
You are correct about this functionality not being available to controllers given that the overloaded .t method is defined in ActionView::Helpers::TranslationHelper. I think this is probably an oversight as opposed to an actual bug.
Off the top of my head there are 2 ways you can get around this in your project :
Call .html_safe in your controller (this worked for me in a quick test).
flash[:notice] = t(:hello_html).html_safe
Send the translation key as the flash message as opposed to the actual message :
Controller :
flash[:translate_notice] = :hello_html
View :
%div= t flash[:translate_notice]
Granted, the latter option might get a bit messy if you need to pass interpolations, YMMV.
I have a controller and I current have it using redirect going to another controller, I know I can pass data around using the :query...
Is there any way I can do this without the use of http as I'm finding it impossible to send a hash using http.
I cant find this information any where, what is the most common way of sharing data (slash sending) data from one controller to another?
please help been working on this for hours, btw am new to RoR
If you are redirecting the browser, you will have to use the query option as redirect actually tells the browser to make another request to a different path.
If you just want to render the other controllers action you could call:
render :template=>"path to view you want to render"
As for actually calling the other action? You could distill (refactor) the logic into a lib and call the same logic from both controllers, then use the same view for both..
I found my answer, I may have not been specific enough with the question. But you can pass a hash using the query string; which obviously (now that I think of it) converts it to a string duh. so I just use eval in the receiving hash,
eval(#params['inputData'] which gives me the hash.
I have a rails 3 app and now i implementing filter for my catalog. Filters form pass data to controller through GET request. As a result i have link like this in my browser after i submit
my form (apply search):
http://localhost:3001/shoes?filter%5BShoeBottomType%5D%5B%5D=2&filter%5BShoeClassification%5D%5B%5D=1&filter%5BShoeClassification%5D%5B%5D=2&filter%5BShoeElation%5D%5B%5D=3&filter%5BShoeElation%5D%5B%5D=4&filter%5BShoeElation%5D%5B%5D=5&filter%5BShoeLiningColor%5D%5B%5D=2&filter%5BShoeLiningColor%5D%5B%5D=3&filter%5BShoeLiningColor%5D%5B%5D=4&filter%5BShoeTopColor%5D%5B%5D=1&filter%5BShoeTopColor%5D%5B%5D=2&filter%5Bonly_action%5D%5B%5D=1&page=2
Is there a way to do URL more beautiful?
PS i dont want use POST request, because I read that it is bad for SEO
TLDR: just leave it.
HTML forms serialize in a straightforward manner; the parameters are named after the HTML elements. The actual issue here is how the form elements are named. It looks like they have names like filter[ShoeBottomType][]; look into your HTML to see the name attributes. Since you're in Rails, I'm guessing you having a filter hash passed to your Rails controller method as a single argument, and since Rails expects hashes to use a certain URL format for hashes and arrays (it has to know how to deserialize it from the request), the form helper writes the form that way. And yours is especially complicated because the hash values are arrays, hence the extra set of brackets. Then it's URL encoded and you end up with an ugly mess.
You could avoid some of this problem by passing the inputs individually back to the controller instead of as a big hash. Something like:
def index
shoe_bottom_types = params[:bottom_types]
shoe_classifications = params[:classifications]
shoe_elations = params[:elations]
...
which will get you to: /shoes?bottomTypes[]=1&bottomTypes[]=2.... That doesn't seem much better, and now your controller is all gross. And I don't see how you're going to get rid of the brackets entirely if you want to have more than one of the same filter. I guess you could get crazy and do your own parsing in your controller, like breaking apart shoeBottomTypes=1|2, but then you'll have to do your own form serialization too. Again, just not worth it.
Backing up for a sec, the SEO stuff doesn't make much sense. Search engines won't fill out your form; they just follow links. The real reason you should use GET is that (presumably), submitting your form doesn't have side effects, since it's just a search. See here; it's important to use the right HTTP methods. If you use POST, you'll get weird warnings on reloads and you won't be able to bookmark the search.
Backing up even further, why do you care, especially now that SEO is out of the picture? Just as a quick demo, I did a google search for the word "thing" and this was the URL:
https://www.google.com/#hl=en&output=search&sclient=psy-ab&q=thing&pbx=1&oq=thing&aq=f&aqi=g2g-s1g1&aql=1&gs_sm=3&gs_upl=764l1877l0l1980l6l6l0l0l0l0l89l432l5l5l0&bav=on.2,or.r_gc.r_pw.r_cp.r_qf.,cf.osb&fp=220ef4545fdef788&biw=1920&bih=1086
So URLs for form submissions can be long. The user won't even look at it.
The only possibility I can think of for why you'd care about the length/ugliness of your URL here is that you want, separately from the form, to create links to certain searches. There are several ways to handle that, but since I don't know whether that's relevant to you, I'll let that be a follow-up.
So bottom line, it looks like I'd expect, and trying to fix it sounds ugly and pointless.
If you do not want to use a POST request, then there is no other way then to put the form values in the URL -- they have to get to the server one way or another.
On the other hand however, I do not see why doing a POST would be bad for SEO and I would love to see the article that stated so.
My suggestion is that you could add some custom routes to beautify your urls.
For example :
http://localhost:3001/shoes/Type/2/Classification/1,2/Elation/3,4,5/LiningColor/2,3,4/TopColor/1,2/only_action/1/page/2
This is far much shorter than your initial URL ;)
The counterpart is that, as far as I know, you have to use always the same order for params in your url.
The routing rule is the following :
match "shoes/Type/:type/Classification/:classification/Elation/:elation/LiningColor/:liningcolor/TopColor/:topcolor/only_action/:only_action/page/:page" => "shoes#show"
You can retrieve the passed values in params array. You have to split the string containing , in order to retrieve the multiple values.
I'm calling a controller action to do a search with an AJAX request from 2 different pages and want to render a different rjs file based on which page requested the action. I could just make 2 actions to do this but it doesn't seem very DRY when it's the same code in the action just need different rjs as it's displaying the search results differently in the view.
Using Rails 2.3.4 and Ruby 1.8.7
If I understand your question correctly, three ways come to mind to solve this:
In your action, check the current request's http_referrer and try to figure out what page initiated the request. Depending on how you've got your routing set up, this may or may not work, but it does have the advantage of being pretty simple to do.
Have your AJAX request include an extra GET parameter to identify which page the request is from. Then, have the Rails action test for that parameter, and render RJS accordingly.
Do something clever with Routes and have page A hit the action from one distinct URL, and page B hit the action from another, and include the page identification parameter in the route configuration.
My preference would be for approach #2, as it seems way less likely to break randomly when your routing changes, and #3 strikes me as being overly complicated. There's probably a million other ways to do this, but those are the three that came to mind right off the bat. Hope that helps...
How much code is in the action? You could just factor that out into a common subroutine and call that from each action. It would keep the code simple and easy to understand, without resorting to clever tricks.
I usually do like #2 from Steven's answer, but with a twist. A filter in my ApplicationController attributes a custom mime type corresponding to the extra parameter.
That way, the names of my view files are clearer (i.e.: "show.employees-autocomplete.rjs", "show.quotation-autofill.rjs").