Conditional in Rails partial depending on the context page? - ruby-on-rails

I was wondering if I could execute / display some stuff differently in partials depending on the context in which it appears.
For example, I have a _user_info partial that appears in a sidebar, and also in the user page, and I want to display some extra info in the second case. How can I express that kind of conditions?

You can use controller_name and action_name methods.
if controller_name == 'user' && action_name == 'show'
details
end

What you're asking for is something this:
if params[:controller].eql?('users')
view code
However I would split the partial into two separate partials and display the distinct parts from whichever view you need.

Sure, it just depends on how you want to discover/expose that context. The simple way is conditionals, which can be set in any number of ways, or derived from a set of conditions. That can happen in a filter, an action, etc.
If the changes are large enough, better to just encapsulate them in separate partials.
Another option is to wrap the render tag in a helper that calculates/grabs those conditions.
It kind of depends on the nature of the conditions, where/how you want to deal with them, etc.

Or pass a variable into the partial via :locals =>

Related

How to handle conditional rendering of views depending on a value passed to the related controller action through a parameter?

I am using Ruby on Rails 3.2.2. I would like to render a show view that should / could be displayed in two different ways depending on a value passed to the related controller action through a parameter. That is, if the parameter is not passed then the show view should be normally rendered else if that value is set to something then the show view should be rendered with some changes (for example, some "embedded" partial templates should change, some information should not be displayed and some other information should be added).
How handle this situation in an efficient / proper way? That is, should I state a conditional rendering in the show controller action and in related views? or should I use a separate controller action so to don't use / pass the mentioned parameter? or should I implement a "separate" / "dedicated" controller in order to handle my "particular" case?
Note: In my case I would like to display different contents "in a public or private way".
It depends on how different these representations are. With two different views you'll end up with certain duplication which can be dealt with by shared partials. If private vs public templates are mostly similar, I'd suggest going with conditionals. You can encapsulate decisions from the beginning by adding helpers which would work like this:
<% if private_view? %>
...
<% else %>
...
<% end %>
or like this:
<%= show_only_when :private do %>
...
<% end %>
But if private vs public representations are vastly different, I'd suggest considering separate controllers. Difference is there for a reason, and will not end at representation.
And for common parts of controllers and views use modules, helpers and shared partials.

How to handle cases in which the generated content depends on the current user authorization?

I am using Ruby on Rails 3.2.2 and, since my system implementation, I would like to generate different outputs (in views) and / or to retrieve different records (in controllers) depending on the "access-er" user authorization (for instance, the authorization could depend on if the "access-ed" user is or not is the current "access-er" user).
How can I handle the situation? That is, for example in order to handle if the user is or not the current user and so to display different content, should I implement two view files and / or controller actions for each case, or should I use if else statements directly in the view file and / or in the controller action?
A cleaner approach I would suggest is to create different roles for users and group them. So for that particular group you can have a separate view files and controllers. One advantage of this approach is it will be very easy to read the code and we can easily understand the code. We get more control on the page easily without having to worry about other users. We can even avoid the need for many filters. But if there is only two type of users then it could be managed easily with if else statement, so choosing the right method will depends on the problem too.
I usually use if else statements right in the views, and render partials if there is a lot of markup between the statements to keep things clean.
That is a style choice though so if you are finding you are making massive conditionals on every page, it could be that you need to rethink your organization in the controller or even make a new resource. For simple things like adding an 'edit' or 'delete' button if the user is an admin, I would use conditionals in the view.
For .html.erb markup, you can do normal if/else blocks like this:
<% if <condition> %>
<%= render 'partial_name' %>
<% else %>
<p>Some other content</p>
<% end %>
Where condition is your condition, like for example current_user? #user

What's the best way to do UJS in rails when you have a re-usable widget?

In my current project I have a couple instances where I have a re-usable form that exists inside a rails partial. This form submits to a specific controller via ajax (:remote => true). The controller does some stuff and then returns back the appropriate js.erb to modify the page via javascript.
This works fine for when I have a single view. But the problem seems to happen when this re-usable partial exists on multiple views. In view 1 I might want to issue a completely different set of javascript commands then in view 2.
As a concrete example, say I have a comments controller that has the normal CRUD operations.
I now have partial called _comments_box.erb. This _comments_box.erb contains the ability to submit a comment via a simple line:
- form_for comment, :url => post_comments_path(post), :remote => true do |f|
This submits to a comments_controller.rb create method which looks somethings like this:
def create
... do some stuff, like create a new comments model
respond_to do |format|
# will respond with create.js.erb
format.js
end
end
The create.js.erb in turn adds a comment to the view, perhaps doing a bunch of other updates to the DOM.
Say I render the _comments_box.erb within a view called post_summary.erb. Now I have another view, post_detail.erb that requires the same _comments_box.erb. However the post_detail.erb requires me to update completely different divs on the DOM in response to a new comment.
I need to create a different JS response for each instantiation. So I can either:
Create an alternate controller method, say create_2. Pass in some parameter to the _comments_box.erb from post_detail.erb to the _comments_box.erb partial so it knows which controller method to fire. This will allow me to have a separate file _create_2.js.erb that will allow me to manipulate the post_detail.erb view independently.
Forget about using js.erb altogether and just use plain old AJAX and get back JSON, and handle the javascript manipulation completely on the client-side.
It seems option 1 allows me to continue to use the UJS supported by Rails which is nice. But also means I probably will be adding a lot of duplicate code everywhere which is annoying. Is there a way for me to do this elegantly while continuing to use UJS?
That's exactly the purpose of Apotomo: http://apotomo.de/
Here is it's own description:
Apotomo is a true MVC widget framework
for Rails. Widgets are based on Cells
and provide reuseable view components.
Having bubbling events, they know when
and how to update themselves via AJAX!
Working with Apotomo widgets almost
feels like developing GUI components –
in a Rails environment.
Have a try, it's great.
I'd not recommend using UJS for frontend apps: server shouldn't take care of client side business. I agree it's useful and clean but it lacks performance and thus should be kept for backend stuff (RJS will move into a gem, see here: http://weblog.rubyonrails.org/2011/4/21/jquery-new-default).
That said, back to the solutions you expose:
1) I think you won't need an extra controller, you'd just have to pass additional params in order to know from where to query came from. A hidden_field could do the trick. With this info, render the good js.erb file
format.js { if condition
render "create.js.erb"
else
render "create_2.js.erb"
end
}
2) I'd go for it and return json but you'll face the same problem: knowing from where the request comes from.
A better solution (than using a hidden_field) might be to check the request.referer in your controller action. This way you leverage the fact that each context has a unique URL, and don't have to explicitly specify another unique value when rendering your widget partial.

Ruby on Rails controller and architecture with cells

I decided to try to use the cells plugin from rails:
http://cells.rubyforge.org/community.html
given that I'm new to Ruby and very used to thinking in terms of components. Since I'm developing the app piecemeal and then putting it together piece by piece, it makes sense to think in terms of components.
So, I've been able to get cells working properly inside a single view, which calls a partial. Now, what I would like to be able to do (however, maybe my instincts need to be redirected to be more "Rails-y"), is call a single cell controller and use the parameters to render one output vs. another.
Basically, if there were a controller like:
def index
params[:responsetype]
end
def processListResponse
end
def processSearchResponse
end
And I have two different controller methods that I want to respond to based on the params response type, where I have a single template on the front end and want the inner "component" to render differently depending on what type of request is made. That allows me to reuse the same front-end code.
I suppose I could do this with an ajax call instead and just have it rerender the component on the front end, but it would be nice to have the option to do it either way and to understand how to architect Rails a bit better in the process.
It seems like there should be a "render" option from within the cells framework to render to a certain controller or view, but it's not working like I expect and I don't know if I'm even in the ballpark.
Thanks!
How would the cell know in which controller it is rendered? This would break encapsulation.
You can use #render_cell in your controller view and maybe put some decider around it? Is that what you're asking for?

Two controllers for one shared view in Ruby on Rails

I have two controllers for two respective models, by example, photos and categories. index and show methods are very similar in each controller, and the views are identical. What is the best method for share the view by the two models?
I've though two options:
Use a helper. In the helper will put the code for the view, and will call the helper from each view (photos/views and categories/views)
Use a partial in each views. I think it's a more clean solution, but I see huge DRY's in my mind when going to code this solution.
So, I have two controllers from two models, each one at and exposes a #photo object (photos controller with all the photos, and categories controller with just the selected categorie's photos) and I need one view to show both.
I'm looking for an elegant solution for this, complaining REST and DRY principes. Any idea?
Thanks in advance.
I have a similar situation with one of my projects. All the delete views for most controllers are styled the same way, display the same confirmation boxes, and simply renders a predictable display of whatever object is being deleted.
The solution was quite simple and elegant in my opinion. Simply put, what we (the developers) did was create a new directory in app/views called shared and put shared views in there. These could be full template files or just partials.
I would suggest using a shared template (in neither categories nor photos view directories, but rather in the shared directory) and rendering it manually from the view.
e.g. have a method as such in both controllers and a file app/views/shared/photo.html.erb:
def show
#photo = Photo.first # ... or whatever here
render :template => 'shared/photo'
end
This should successfully render the shared template. It is the DRYest route and doesn't have the feeling of pollution you get when using a more-or-less empty view in each controller's view directory just to include a shared partial, as I understand your question is suggesting.
About the first answer:
If the partial must be rendered from a view:
<%= render :partial => "shared/photo" %>
and the partial must be in app/views/shared/_photo.html.erb
I'd use an helper because they are shared among views. For the HTML part, I'd use partials so it would be a mix of both ways.
This looks like a good use case for the Cells gem.
#bjeanes If all your delete views are the same, you can create views/default/delete.html.erb and all the delete actions will use it.
That's what i'm doing: Most of my views are on default, and i create specific ones only when needed
Update: Ok, this post is from 2009, anyway, i will keep my comment here in case someone gets here from Google like i did.

Resources