I'm using fragment caching a lot and it is essential to me for good performance. However, due to the complexity of the caching I'm using, I need to offer my testers, a way to disable/enable caching as a session variable. (On a user basis only)
I was thinking about implementing a cache_disabled? method, and I now check for it's value everywhere I use cache. Now, I'm stuck with the following piece of caching, and I can't figure out how to nicely integrate this check :
<% cache(#cache_key_for_consultContent) do %>
<div id="consult">
<%= render :partial => 'LOTS_OF_CONTENT' %>
</div>
<% end %>
I need the content to be called when caching is disabled or content isn't cached yet.
thanks for your creativity! (Please keep it DRY)
In your application helper you could try:
def optional_cache(key, &block)
cache(key, &block) unless session[:disable_caching]
end
Then replace your calls to cache() with optional_cache().
Related
In my app users can submit recipes through a form, which will be published on a website. Before recipes get published they are moderated through a moderator.
Therefore my app shows in the navbar a count of all currently unpublished recipes for the moderator like so:
To achieve this at the moment I do the following:
application.rb
before_action :count_unpublished
def count_unpublished
#unpublished_count = Recipe.where(:published => false).count
end
_navbar.html.erb
<li>
<%= link_to recipes_path do %>
Recipes <span class="badge" style="background-color:#ff7373"><%= #unpublished_count %></span>
<% end %>
</li>
It works, but I am wondering now if this is a good practice as now with every action my app hits the recipe database (which is maybe not very elegant).
Is there a better solution to achieve this?
cache_key = "#{current_user.id}_#{unpublished_count}"
#unpublished_count = Rails.cache.fetch(cache_key, expires_in: 12.hours) do
Recipe.where(:published => false).count
end
For More: http://guides.rubyonrails.org/caching_with_rails.html#low-level-caching
To avoid hitting the database, you can introduce caching. It comes in many forms: faster storage (memcached, redis), in-process caching (global/class variables) and so on. And they all share the same problem: you need to know when to invalidate the cache.
Take a look at this guide to get some ideas: Caching with Rails.
If I were you, I would not care about this until my profiler tells me it's a performance problem. Instead, I'd direct my efforts to developing the rest of functionality.
Your falling into the trap of premature optimisation. Before doing any optimisation (which increases code complexity most of the time) you have to profile your code to find the bottleneck. Improving a SQL requests which counts for a small part of the total response time is useless. In the contrary if the SQL takes a big amount of time, that is a great improvement.
For that I can recommend these 2 gems:
https://github.com/miniProfiler/rack-mini-profiler
https://github.com/BaseSecrete/rorvswild (disclaimer: I'm the author of this one)
To reply to your question, the better way would be:
# app/models/recipe.rb
class Recipe < AR::base
# A nice scope that you can reuse anywhere
scope :unpublished, -> { where(published: false) }
end
Then in your navbar.html.erb:
<li>
<%= link_to recipes_path do %>
Recipes <span class="badge" style="background-color:#ff7373"><%= Recipe.unpublished.count %></span>
<% end %>
</li>
You have no more these ugly callback and instance variable in the controller.
Unless you have a lot of recipes (something like 100K or more) performance won't be an issue. In that case you can add an index:
CREATE INDEX index_recipes_unpblished ON recipes(published) WHERE published='f'
Note that the index applies only when published is false. Otherwise it would be counter productive.
I think that caching in your case is not well because the invalidation is extremely complex and leads to awful and easy breakable code. Don't worry to hit the database, we will never write faster code than PostgreSQL/MySQL, etc.
I came across the view helper function "provide" today. By looking into its manual I am still confused on how it is different from "content_for".
provide(name, content = nil, &block)
The same as content_for but when used with streaming flushes straight
back to the layout. In other words, if you want to concatenate several
times to the same buffer when rendering a given template, you should
use content_for, if not, use provide to tell the layout to stop
looking for more contents.
Question 1: this is quite abstract to me - could anyone flesh it out by giving a demonstrative example?
Question 2: working with asset pipeline, which performs better and why?
Thanks!
First of all, what is streaming? Why would you use it?
Streaming is alternate method of rendering pages top-down (outside-in). The default rendering behavior is inside-out. Streaming must be enabled in your controller:
class MyController
def action
render stream: true # Streaming enabled
end
end
According to the documentation:
Streaming may be considered to be overkill for lightweight actions
like new or edit. The real benefit of streaming is on expensive
actions that, for example, do a lot of queries on the database.
So, if you're not using streaming, is there still a difference?
Yes.
The difference is a template can define multiple content blocks by calling content_for multiple times. Doing so will concatenate the blocks and pass that to the layout:
# layout.html.erb
<div class="heading"><%= yield :surprise %></div>
<div class="body">
<p><%= yield %></p>
<p>But it's not very interesting...</p>
</div>
# template.html.erb
<%= content_for :surprise, "Hello" %>
I've got your content!
<%= content_for :surprise, ", World!" %>
# Generated HTML
<div class="heading">Hello, World!</div>
<div class="body">
<p>I've got your content!</p>
<p>But it's not very interesting...</p>
</div>
Since provide doesn't continue searching the provided template, only the block passed to the first provide call will be sent to the template:
# layout.html.erb
<div class="heading"><%= yield :title %></div>
# template.html.erb
<%= provide :title, "Foo" %>
<%= provide :title, "bar" %>
# Generated HTML
<div class="heading">Foo</div>
Was curious to see what the difference was, and as Thong Kuah pointed to the api, inside the answer:
This means that, if you have yield :title in your layout and you want to use streaming, you would have to render the whole template (and eventually trigger all queries) before streaming the title and all assets, which kills the purpose of streaming. For this reason Rails 3.1 introduces a new helper called provide that does the same as content_for but tells the layout to stop searching for other entries and continue rendering.
I'm using fragment cache but i have inline code that is user specific like:
<% cache #page do %>
stuff here
<% if current_user %>
user specific
<% end %>
more here
<% end %>
So i want to exclude the several blocks of code that are user specific. Is there a way to do that in Rails or should i make an if statement in the beginning and make different caches for logged users and regular visitors? (i will have major duplication of code this way).
For per-user fragments, you can put models in array an array:
<% cache [#page, current_user] do %>
Rails will make a cache-key out of them, like:
pages/page_id-page_timestamp/users/user_id-user_timestamp
This way your fragments will be invalidated on a user/page update since the time-stamps are coming from their updated_at (see cache_key for details).
I'm curious about the efficiency of the Rails current_page? helper method. I'm using it in a view, roughly as shown below:
<% if current_page?(:action => "foo") %>
<dt>Label 1:</dt>
<% else %>
<dt>Label 2:</dt>
<% end %>
and
<% if current_page?(:action => "foo") || current_page(:action => "bar") %>
<dt>Label 1:</dt>
<% else %>
<dt>Label 2:</dt>
<% end %>
But would it be more efficient to make this switch some other way? For instance, would it be more efficient to set an instance variable in my controller actions for foo and bar, then check <% if #foo || #bar %>?
And is there any difference in the efficiency between Rails 2 and Rails 3?
I can't speak to the difference between Rails 2 and Rails 3, but looking at the source code in ActionPack, it doesn't look like the method is doing anything particularly complicated. url_for could be slightly inefficient (I don't know offhand), but unless you're doing a huge number of loops over this partial, optimizing this is probably not going to save you a noticeable amount of time.
That said, it would be easy to do some basic benchmarks -- t = Time.now; loop 1000 times over one version; v1_time = t - Time.now; t = Time.now; rinse and repeat with the other version. If you do it, let me know what you find.
All that said, it seems to me that it would be probably be cleaner conceptually to have your controller methods set appropriate flags, if the flags could be expressed as concepts not directly related to the view. I'd be curious what others think.
Warning: Noob here.
I know this is a trivial subject but I'm having a lot of difficulty in figuring out how exactly I can simplify my views by moving parts of them into helpers. For example, I've always read that conditionals in your views are prime candidates for extraction into helpers, but I couldn't really find examples of this, and my attempts to achieve this failed.
For example, suppose I have:
#index.html.erb
<% for beast in #beasts do -%>
<% if beast.dead? -%>
<%= beast.body %>
<%= link_to "bury", bury_beast_path( :id => beast.id ) %>
<% else -%>
<%= beast.body %>
<%= link_to "kill!", kill_beast_path( :id => beast.id ) %>
<% end -%>
<% end -%>
It annoys me a little to have this in my view, but how exactly could I move this to a helper instead? And further simplify it, if possible. (I've read somewhere that conditionals are bad but it's just beyond me how you could program anything without them.)
Another example: I need to id my body tags with the format controller_action. The best I've got so far is this:
#index.html.erb
<body id="<%= controller_action %>">
…and…
#application_helper.rb
def controller_action
#id = #controller.controller_name + "_" + #controller.action_name
end
I'm no expert, but that's still ugly even to me.
To make things more complicated, Ryan Singer said something I liked: to treat ERB like an image tag, using helpers to "reveal intention". Then in the next breath saying that you should have no HTML in helpers for that is the way to hell. WTF? How are both things compatible? If it's come to the point where you can just declare behaviors in the view, surely there should be a lot of HTML to be rendered behind the scenes? I can't grasp it.
So, that's basically it. I'd appreciate if anyone could share some thoughts on this, or point me to some good in depth reading on the subject – which I've found to have a really weak coverage on the web. I've already googled it to exhaustion but who knows.
Refactoring makes your views easier to maintain. The problem is choosing where the refactored code goes.
Your two choices are partials and helpers. There's no stone-set rules dictating which should be used where. There are a couple of guidelines floating around like the one stating that helpers should not contain HTML.
Generally partials are better suited for refactoring sections that are more HTML/ERB/HAML than ruby. Helpers on the other hand are used for chunks of ruby code with minimal HTML or generating simple HTML from parameters.
However, I don't agree with the sentiment that helpers should contain no HTML at all. A little is ok, just don't over do it. The way helpers are processed hinder their use for producing large amounts of HTML. Which is why it's suggested that your helpers contain minimal amounts of HTML. If you look at the source the helpers that ship with rails you will notice that most of them generate html. The few that don't, are mainly used to generate parameters and evaluate common conditions.
For example, any of the form helpers or link_to variants fit the first form of helpers. While things like url_for and logged_in? as supplied by various authentication models are of the second kind.
This is the decision chain I use to determine whether to factor code from a view into a partial or helper.
Repeating or nearly identical statements producing a single shallow html tag? => helper.
Common expression used as an argument for another helper? => helper.
Long expression (more than 4 terms) used as an argument for another helper? => helper.
4 or more lines of ruby (that is not evaluated into HTML)? => helper.
Pretty much everything else => partial.
I'm going to use the code you're looking to refactor as an example:
I would refactor the view in the question this way:
app/helpers/beast_helper.rb:
def beast_action(beast)
if beast.dead?
link_to "bury", bury_beast_path(beast)
else
link_to "kill!", kill_beast_path(beast)
end
end
app/views/beasts/_beast.html.erb:
<%= beast.body %>
<%= beast_action(beast) %>
app/views/beasts/index.html.erb:
<%= render :partial => "beast", :collection => #beasts %>
It's technically more complicated, because it's 3 files, and 10 lines total as opposed to 1 file and 10 lines. The views are now only 3 lines combined spread over 2 files. The end result is your code is much more DRY. Allowing you to reuse parts or all of it in other controllers/actions/views with minimal added complexity.
As for your body tag id. You should really be using content_for/yield. For that kind of thing.
app/views/layouts/application.html.erb
...
<body id="<%= yield(:body_id) %>">
...
app/views/beasts/index.html.erb
<% content_for :body_id, controller_action %>
...
This will allow you to override the id of the body in any view that requires it. Eg:
app/views/users/preferences.html.erb
<% content_for :body_id, "my_preferences" %>
The first thing I'd do would be this:
#index.html.erb
<%= render #beasts %>
#_beast.html.erb
<%= beast.body %>
<%= link_to_next_beast_action(beast) %>
#beast_helper.rb
def link_to_next_beast_action(beast)
if beast.dead?
link_to "bury", bury_beast_path( :id => beast.id )
else
link_to "kill!", kill_beast_path( :id => beast.id )
end
end
What I've done is separate out the rendering of the beast into a partial which uses collection semantics.
Then I've moved the logic for showing the kill/bury links into a beast helper. This way if you decide to add another action (for example, 'bring back from dead'), you'll only have to change your helper.
Does this help?
A third choice is to use a view model from the Cells gem. This is a very popular framework that brings object-orientation to the view layer in Rails.
# app/cells/beast/cell.rb
class Beast::Cell < Cell::Concept
def show
return dead if model.dead?
kill
end
private
def dead
link_to "bury", bury_beast_path( :id => model.id )
# you could render a view here, too!
end
def kill
link_to "kill!", kill_beast_path( :id => model.id )
end
end
You then render a view model using a helper (in the view or controller).
# app/views/beasts/index.erb
<%= concept(:beast, #beast).call %>
<%-# this returns the link content %>
That's all! You can test this cell isolated in a separate test. Cells also give you view rendering, view inheritance and many more things.
As an example, you could use a view for the kill link.
# app/cells/beast/cell.rb
class Beast::Cell < Cell::Concept
# ..
def kill
render :kill
end
end
This renders the cell's killer view.
# app/cells/beast/views/index.erb
<%= link_to "kill!", kill_beast_path( :id => model.id ) %>
Note the location of the view, it's nicely packaged into the cell directory.
And, yes, cells can do HAML and any other template engine supported by AbstractController.
Another startegy would be to not use templates and helpers at all.
For rendering you could :
render your views directly from your controllers using render(:inline => ). If you still want to keep Views and Controllers formally separated you can create modules / mixins that you include into the controllers.
or create your own view classes and use them to render your response.
The idea behind this is that helpers and rails erb templating system don't take advantage of OOP, so that at the end of the day you can't define general behaviours that you'll specialize according to each controller's/request's needs; more often than not one ends up rewriting very similar looking chunks of code, which is not very nice from a maintenance standpoint.
Then if you still need some helper methods (eg. form_tag, h, raw, ...) you only have to include them in your controller / dedicated view class.
See this : rails-misapprehensions-helpers-are-shit for a fun but useful article.
EDIT: to not sound like a complete douche, I'd say implementing this depends on how big your application is supposed to be, and how often you're going to have to update your code. Plus, if you're delegating the design to a non-programmer, he/she may well be in for some programming courses before digging into your code, which admittedly would be less directly understandable than with templates syntax.