Ruby on Rails: caching data in an object - ruby-on-rails

I've come up with an issue I can't figure out how to solve. I'm new to both Ruby and Rails, and sure there is a simple way to achieve what I'm looking for.
This is the ERB of the show view, showing two equal lines:
<p><%= #user.foo %></p>
<p><%= #user.foo %></p>
Imagine that foo is an intense computational method so I want to cache the result of the first call in order to use it in the second line without having to call foo again. The simplest option would be defining a variable and cache it:
<% foo_cache = #user.foo %>
<p><%= foo_cache %></p>
<p><%= foo_cache %></p>
But I don't want to clutter the "global" scope. A nicer way would be that foo itself could save a cache of the value it returns when it's called the first time:
def foo
return self.cached_foo if self.cached_foo #WARNING: pseudocode here!
#Not cached. Do stuff
...
self.cached_foo = computed_value
computed_value
end
My question is if it's possible to attach data to an object instance dynamically without interfering with the model behind (i.e. without making save and company functions deal with this attached data). Or maybe is there another better way to achieve what I'm looking for?
Thanks.

This is called memoization and it's a common idiom in ruby. It is usually expressed like this:
def foo
#cached_foo ||= begin
# do your heavy stuff here
end
end
#cached_foo should not interfere with ActiveRecord (like make it try to save cached_foo to the database).

What you are looking for is called memoization
def foo
#foo ||= calculate_foo
end
def calculate_foo
# heavy stuff
end
This works thanks to conditional assignment (the||=)
It's an extensive topic so I'll leave you a couple of links about it:
http://rails-bestpractices.com/posts/59-use-memoization
http://gavinmiller.io/2013/basics-of-ruby-memoization/
Plus advanced memoization in case you need to do more complicated stuff such as parameters, storing nil values
http://gavinmiller.io/2013/advanced-memoization-in-ruby/
In fact Active Support had memoizable but it was deprecated and then extracted into a gem
In case you want to use it check it out on:
https://github.com/matthewrudy/memoist

This should do it. And don't be afraid, the instance variable has no impact on the persistence layer.
def foo
#foo ||= compute_foo
end
private
def compute_foo
# ...
end

Related

Refactoring following lines of code

- if clean_book_intro_component(:literary_works).present?
%h2 Other Books Related to #{#book.title}
%p.fact-text
= clean_book_intro_component(:literary_works)
Can above code written by calling clean_book_intro_component(:literary_works) only once?
Implementation of clean_book_intro_component
def clean_book_intro_component(component)
sanitize #book.intro.send(component), tags: %w(span b i p a), attributes: %w(id class style href)
end
- clean_book_intro_component(:literary_works).tap do |cbic|
- if cbic.present?
%h2 Other Books Related to #{#book.title}
%p.fact-text
= cbic
maybe I got haml wrong, but the idea is to use tap instead of explicitly saving the result of the call
Assigning variables in view is generally not recommended. However, in this case you can use an inline assignment which is generally accepted (as long as you keep the usage scoped within the context of the condition block):
if (intro = clean_book_intro_component(:literary_works)).present?
%h2 Other Books Related to #{#book.title}
%p.fact-text
= intro
Another solution is to memoize the value inside the function.
def clean_book_intro_component(component)
#component ||= {}
#component[component] ||= sanitize #book.intro.send(component), tags: %w(span b i p a), attributes: %w(id class style href)
end
However, this will cause the interpreter to retain the data as long as there is a reference to the instance. Therefore, this is recommended only in very particular cases where the execution is expensive and/or the data to be memoized is limited.
Moreover, it requires some extra complications if the helper accepts parameters. In fact, you will end up memoizing an amount of data which is linear with the possible input of the parameters.
Yes, just save the result of clean_book_intro_component(:literary_works) in a variable and then use that variable instead of invoking the function.
You could move the view into a partial and call the partial on a collection. If the collection is empty nothing is rendered. Something like:
# a related_books partial
%h2 Other Books Related to #{#book.title}
%p.fact-text
= related_books
# in the calling view
= render partial: related_books, collection: [clean_book_intro_component(:literary_works)]
See the Rails Guide about rendering collections.

Low level caching for collection

I want to use Redis to do some low level caching in my Rails app.
In a controller I normally us this to get all books:
class BooksController < ApplicationController
def index
#books = Book.order(:title)
end
end
And the view iterates over this:
<ul>
- #books.each do |book|
<li>= "#{book.title} - #{book.author}"</li>
</ul>
Now I want the exact same result but then cached. I have Redis setup and running. So should I use a cached_books method in the controller like this:
#books = Book.cached_books.order(:title)
And leave the view as it is, or use book.cached_title and book.cached_author in the view and leave the controller as it is?
And how would a cached_books method look like in the Book model?
class Book < ActiveRecord::Base
...
def cached_books
Rails.cache.fetch([self, "books"]) { books.to_a }
end
end
For simplicity sake I leave out expire strategies for now, but obviously they need to be there.
So should I use a cached_books method in the controller like this:
Yes, you can. Although there's some gotchas you have to be aware of.
Book is ActiveRecord. When you call Book.something (e.g. Book.all, or just even Book.order(:title) it returns you a ActiveRecord::Relation, which is basically wrapper for array of Books (this wrapper prevents of firing unnecessary queries, boosting perfomance).
You can't save the whole result of a query in Redis. Say, you can save a JSON string of an array of hashes with model attributes, e.g.
[{
id: 1,
title: 'How to make a sandwich",
author: 'Mr. cooker'
}, {
id: 2,
title: 'London's Bridge',
author: 'Fergie'
}]
And then you can 'decrypt' this thing into the array after. Something like
def cached_books(key)
# I suggest you to native wrapper
if result = $redis.hget 'books_cache', key
result.map do { |x| Book.new(x) }
end
end
And also, you will have to serialise attributes before putting them into the cache.
Ok, now you have collections which can be iterated in the view with same data, although you can't call order on a cached collection, as it is a plain array (you may call sort, but the idea is to cache already sorted data).
Well... does it worth it? Actually, not really. If you need to cache this piece – probably, best way is to cache a rendered page, not a query result.
Should you use cached_title and cached_author – that's the good question. First of all, it depends on what cached_title may be. If it is a string – there's nothing you can cache. You get a Book through DB request, or you get Book from cache – in any way the title will be presented in it, as it is a simple type. But let's look closer to the author. Most likely it is going to be a relation to another model Author and this is the place where cache suits perfectly great. You can re-define author method inside the book (or define new and avoid nasty effects Rails may have in complex queries in the future) and see if there's a cache. If yes, return the cache. If not – query the DB, save result to the cache and return it.
def author
Rails.cache.fetch("#{author_id}/info", expires_in: 12.hours) do
# block executed if cache is not founded
# it's better to alias original method and call it here
#instead of directly Author.find call though
Author.find(author_id)
end
end
Or less convenient, but more "safe":
def cached_author
Rails.cache.fetch("#{author_id}/info", expires_in: 12.hours) do
author
end
end

Ruby on Rails: proper way to return data from methods

How do I follow OOP standards within RoR controllers?
The setup: submitting data to a form & then manipulating it for display. This is a simplified example.
app/controllers/discounts_controller.rb
...
def show
#discount = Discount.find(params[:id])
formatted = calc_discounts(#discount)
end
...
private
calc_discounts
half_off = #discount.orig_price * .5
quarter_off = #discount.orig_price * .25
return {:half => half_off, :quarter => quarter_off}
end
...
Or is it better to place this in a library with attr_accessor and then create new instances of the library class within the controller? Or is there an even better way of accomplishing this?
The question to ask yourself is "is this logic useful for the view, model, or both?"
If the answer is that it's only useful for display purposes, I would put that logic in a view helper. If it's also beneficial to the model, put it there. Maybe something like this:
class Discount
def options
{half: (self.orig_price * .5), quarter: (self.orig_price * .25)}
end
end
Then in your controller you can just locate the record in question:
def show
#discount = Discount.find(params[:id])
end
And display it in the view:
<h1>half: <%= #discount.options[:half] %> </h1>
<h1>quarter: <%= #discount.options[:quarter] %> </h1>
Well, you can can add half_off and quarter_off as methods to your model:
class Discount < ActiveRecord::Base
def half_off
orig_price * 0.5
end
def quarter_off
orig_price * 0.25
end
end
.. and then do the following:
def show
#discount = Discount.find(params[:id])
end
Now you can call #discount.half_off and #discount.quarter_off in your view..
First off, you've got some syntax issues there. When you define methods you need to use a def keyword, and since Ruby 1.9 you can use a shortcut when defining hashes that avoids hashrockets, so it's:
def calc_discounts
half_off = #discount.orig_price * .5
quarter_off = #discount.orig_price * .25
return {half: half_off, quarter: quarter_off}
end
Also, you defined a local variable formatter inside of your controller's show method. This doesn't actually do anything but assign some values to a variable that only exists within that method. Only the controller's instance variables (variables with an #) can be passed to the view.
That being said, the best practice in RoR is to keep controllers "skinny", which means only using controllers to authenticate, authorize, load a model, assign an instance variable for you view, handle errors with any of the former, and then render the view according to the format requested.
It's another best practice not to include much logic in your views. This way, your logic can be shared with and reused by other views instead of having to be re-written for each new view you make. It also makes your views more readable, as they will read like simple lists of what is to be shown instead of making people try to decipher embedded ruby all over the place.
If the code is something that one of your other models could benefit from being able to use, put it inside your model code (or make a new plain old Ruby object if the logic is complex or not really cohesive with the existing model).
If the logic is something that is just for making a view prettier or in a better format, but won't actually be used by the models, then it should go in some type of view helper or decorator.

simple ruby method helper

I am just learning ruby and wanting to practice writing little helper methods for rails as a good way of revising the basics.
all I would like to do is provide a counter for scoped objects.
so in my view i write this
=stats_counter_for(with_pending_state)
'pending_state' being a particular scope of the model.
def stats_counter_for(object_state)
Photo.object_state.count
end
so i want to pass this through to provide a count of all items with a pending state.
so eventually I can do
=stats_counter_for(with_active_state)
=stats_counter_for(with_inactive_state)
(the equals is from the haml view)
update error message
undefined local variable or method `with_pending_state' for #<#<Class:0x007fbce1118230>:0x007fbce1123770>
=link_to '/ Pending Approval', pending_admin_entries_path
=stats_counter_for(with_pending_state)
=link_to '/ Rejected', rejected_admin_entries_path
Where am I going wrong here? I am sure this is incredibly simple.
You can use the send method:
def stats_counter_for(state)
Photo.send("with_#{state}_state").count
end
So in your views you can use it like that:
= stats_counter_for(:active) # or as a string 'active'
= stats_counter_for(:inactive)

extract string of method names from database?

I am trying something new and I'm stubborn, so I want to exhaust all possibilities.
I have a model called navbar with a field for links.
Inside the links field, I have stored a number of words:
profile_link community_link
The words are significant, in that, they are also the names of methods I have recorded in navbars_helper:
module NavbarsHelper
def profile_link
link_to current_user do
image_tag(current_user.image.img.mini_avatar)
current_user.name
end
end
def community_link
link_to 'Community', topics_path
end
...
end
The new thing I was trying, was to extract the words from the string and use them to call the methods in my header layout:
- if signed_in?
- #current_group.navbars do |navbar|
- if navbar.kind == "Header"
= navbar.links.to_s
navbar belongs_to group
So, what I get is the string in the header: profile_link community_link
But, what I want is a call to the methods. Is this possible? If so, can you tell me how you would do it?
I'm not very experienced working with arrays and I think it may have something to do with
I guess that it could be made working, although I am not really sure if it is worth: you are adding a lot of complexity for almost no additional benefit.
Said that, something along the lines of
- if signed_in?
- #current_group.navbars.each do |navbar|
- if navbar.kind == "Header"
- navbar.links.split(' ').each do |method|
= self.send(method)
Basically, take the string "profile_link community_link", split it using the space character and then send each method to the view (which is self in this context). Using send just executes the method as you would do normally, but gives you the benefit of deciding which method to execute at runtime :)

Resources