Multiple dynamic method calls or declaring a variable in Grails - grails

In my view, if I have a situation where I need to use a dynamic method (such as Domain.findByName("name")) in multiple places, would it be better to define a variable with and refer to that, rather than have the dynamic method in multiple places? I know this seems like an obvious answer, but I just wanted to make sure Grails doesn't cache it or something, and indeed two DB calls are being made.

By default, grails will only cache "get" requests (i.e. Book.get(4)), if you don't set up any additional caching, you'll hit the database for each request (as you're seeing).
See the 'caching queries' section of the grails documentation for more detail.
If you only want the call to be made once (which makes sense in a view since you'd want it to be consistent), I'd either do the query in the action and pass it in the model, or else you could also use the g:set in your view to set it (though this sounds like it's more appropriate for a controller or service).

It would be better to send the domain object to the view as part of the model, rather than calling Domain.findByName("name") from your view.
So in your controller method you'd want
def myAction = {
def myObject = Domain.findByName("name")
// do other stuff
[myObject: myObject]
}
then in your view you can access it by
${myObject.property}

Related

Accessing session data from a layout

In my ASP.NET MVC solution I have a number of services.
One of them, SessionService, is used to access the currently selected region and time span.
I want to display those in a layout used to decorate views. What is the best design approach to access those values which are stored in the SessionService?
Right now I'm thinking about using calling a ChildAction from the layout which in turn calls the session service:
_Layout -> aController.ChildAction() -> SessionService.GetRegion()
Is it a good approach or can you recommend anything better?
UPDATE 1:
Other options for passing the values that are possible:
via ViewBag
via ViewModels
However the drawback for these options is the fact that it would be necessary to populate them in each and every action method which would lead to duplication of code (which could be mitigated by means of a filter, but again this will require decorating controllers with the filter).
UPDATE 2 (born in the discussion with O:rvar below):
Another option is to create a base controller which will be populating ViewBag properties upon creation. All other controllers should derive from it.
You should be able to access you session data in the view with the following code:
var region = #Session["Region"].ToString();
Or you could call the controller method as you mentioned with an ajax call and get the session data that way. Using the childaction approach is also a fine way of accomplishing what you want.

Using model directly in the view in Rails

I have a model named "Category". It is just a list of descriptions stored in the database. Now I want the category descriptions to appear in a drop down list.
Would the correct thing be to make an instance variable in the action where I say something like #categories = Category.all or do you use Category.all directly in the view?
What would be the shortcomings/advise against using the model directly in the view?
If Category.all is being called in the view only once, it's OK to write it directly. Else, it's better to write a helper rather than creating instance variables as per Rails convention. Something like
def all_categories
#all_categories ||= Category.all
end
It does a single query, if being used multiple times in the same view as well.
A common practice is to create the instance variable in the controller for the data which is specific to that request.
For you Category example, doing the query directly from the view is appropriate.
Could be in the view for that action, a partial, or even in the layout if it's used throughout the site.
A simple rule of thumb is to only save method results in instance variables if it saves you some code duplication because you want to use the result twice. Another rule of thumb is to never call methods that have side effects in your views. In this case it seems you are using a method without side effects once, so I would be okay with putting it in a view.
That said it is a lot easier to lose sight of your model method calls in your views than in your controller since they are mixed with the markup elements. That might cause you to overlook that you have called Category.all before when adding some new code in your view that also calls Category.all. Instead of easily noticing in your controller that you have an instance variable for Category.all, you are stuck with either going through your whole view or forgetting to do so.
Another case to make for using instance variables is that it can make your views easier to reuse. Instead of tightly coupling your view to the Category class, you might want to make the calls that are done on the instance variable generic enough to also be applicable to other models that can be viewed in a similar way. Using instance variables this way can help you take advantage of the duck typing that Ruby offers, but you have to weigh the ease of making things generic against the effort of remembering or looking up what kind of methods are actually available on the different kinds of objects that could be inside your instance variable.

ASP.NET MVC - How to best build a form action that can respond in many ways?

I am in the process of writing a web app that includes a reporting form. This form contains a number of radio buttons that allow the user to specify the return data.
There are about 6 different return data 'formats', and each of those has two variations - html data or JSON data for rendering to a chart.
I have begun coding it up and already my form post action method feels wrong.
I basically have a check on the requested data format and return it as needed. Each return type requires its own partial view / json object so there is little room for reusing code.
It feels like each one should have its own action method. Having the form post to different locations based on a radio button choice also feels wrong though.
Switching on report type and then redirecting to the appropriate action in the controller also feels like its not quite right.
Am I approaching this in the wrong way? As it currently stands my controller action contains a lot of code and a lot of logic...
Hope my query makes sense.
Thanks
I don't think there is anything wrong with your approach. To maximize reuse you could:
include reusable templates inside your views
make sure the business/data layer code is the same everywhere (where possible)
I suppose the views you need to return actually are different for each combination of options so whatever approach you take, you are stuck with that.
I wouldn't opt for the client-side approach. You then have code on both the server and the client that has to be updated whenever you change anything. I would keep the code that receives a set of options and determines what to do with them in one place.
I know what you mean about it feeling like each format should be a separate action, but maybe a hybrid approach would make it feel better.
If you set the value of each radiobutton to the name of the action it relates to, you then, in your main POST action, have a parameter that you can use to call the appropriate action in one line of code. You don't have to fudge anything in Javascript, it's easily extensible, and you get your separate actions.
If I understand your problem right you have a lot of switch code in action.
I think you can use Factory pattern. You can create factory that will accept switch parameter as parameter and will return ActionResult instance.

What is a preferred way of displaying result as a table?

I have an action that populates the result from the DB. Right now, I see a way of doing it and that is to make the Action ServletRequestAware, set the populated list as a request attribute and show it in jsp.
Since a lot of improvements have been introduced into struts2, is there any other way of doing that? The first thing that comes to my mind is to use displayTag and change the return type of Action to a List, but that does not seem to work.
Thanks for any replies in advance.
You question is unclear, you should read some book about Struts2 to get the general idea.
No need to make the Action ServletRequestAware. The mapping from http parameters to actions fields is automatically done via the Param interceptor (already set in the default configuration). And one of the points of Struts2 is decoupling the action from the http protocol, you should not (typically) do anything related to http in your action.
Tipically, in your action execute() method (or whatever) you'll get the data to display from the DB and set it as one property of your action, so that is accesable from some getter.
Then, in your view page (JSP or whatever) you'll display it. You can use displayTag, but first you'll prefer to display it "manually", to understand what's involved. See for example here http://www.roseindia.net/struts/struts2/struts2controltags/iterator-tag.shtml
For manually displaying a table, also see this example http://www.vaannila.com/struts-2/struts-2-example/struts-2-crud-example-1.html , search for the <table class="userTable> tag.

Rails STI Controllers

I have a Rails site using STI with the following classes:
Pages
Homepage < Pages
LandingPage < Pages
On the front-end all requests get handled by the Pages controller. However, if the object detected is actually an instance of LandingPage, i'd like to have the action on a LandingPages controller get called. (for example, the show method in the child controller classes will pull in some specific lookups that aren't always relevant).
Any suggestions on how to best accomplish this?
Thanks
This sounds a bit like you are clouding the MVC distinction, but it should be doable.
I'd add a series of tests on the Pages model (e.g. supports_buzzbar_foo? or wiggums_itemization_controller, then override them as appropriate in the subclasses) and use these in the view to conditionally generate the appropriate links to the controller methods you want.
That way you're keeping each part (roughly) doing it's job.
Markus' solution should work. You could also keep your links in the views pointed to Pages, evaluate the incoming object and then redirect_to the appropriate controller based on the object class.
However, unless you're performing completely different actions with each type of object, then you'll wind up with duplicate code in your controllers. So you might be better off sticking with the Pages controller and just adding some methods that handle the extra lookups that are needed for that object.

Resources