Caching in Ruby on Rails
Good article on this topic:
http://www.sitepoint.com/speed-things-up-by-learning-about-caching-in-rails
And official docs are also a good source of information:
http://guides.rubyonrails.org/caching_with_rails.html
almost home
dirt enthusiast

Discoholic 🪩
RMH
AnasAbdin
hello vonnie
Claire Keane

Product Placement
Sade Olutola

Kaledo Art
One Nice Bug Per Day
will byers stan first human second
$LAYYYTER

Love Begins
ojovivo

Andulka

No title available

No title available

PR's Tumblrdome
noise dept.

seen from Singapore

seen from Indonesia
seen from Türkiye

seen from United States

seen from Russia

seen from Canada
seen from United States
seen from Australia

seen from United States
seen from Japan
seen from United Kingdom

seen from United States
seen from Argentina
seen from United States

seen from Türkiye
seen from Malaysia
seen from Chile

seen from Indonesia
seen from United States
seen from Italy
@webdeveloperdiary
Caching in Ruby on Rails
Good article on this topic:
http://www.sitepoint.com/speed-things-up-by-learning-about-caching-in-rails
And official docs are also a good source of information:
http://guides.rubyonrails.org/caching_with_rails.html
Google DFP + Turbolinks
http://reed.github.io/turbolinks-compatibility/doubleclick_for_publishers.html
Google Analytics and Turbolinks in Rails
I found rack-tracker - it’s a instant Google Analytics implementation into your rails app.
It also works with Turbolinks (with just small change).
Installation
Gemfile:
gem 'rack-tracker'
config/application.rb:
config.middleware.use(Rack::Tracker) do handler :google_analytics, { tracker: 'UA-11111111-1', position: :body } end
Don’t forget add that `position: :body`, thanks to this it will work with Turbolinks. Also don’t forget replace UA-11111111-1 with your own GA code of course.
Heroku
In case your rails hosting is Heroku, use ENV variables instead of harcoded values. Then you can change tracking ID anytime from the terminal.
First, set new Heroku variable with your tracking code in value:
heroku config:set GA_TRACKING_CODE=UA-11111111-1
Then config/application.rb:
config.middleware.use(Rack::Tracker) do handler :google_analytics, { tracker: ENV['GA_TRACKING_CODE'], position: :body } end
That’s it!
Your rails environment in single command
To open all tools for your Rails project you’re working on, you would normally `cd` to the project folder, run rails server, open text editor and open localhost:3000.
In other words, you repeat the same set of actions every time you’re switching between projects.
Solution
Let’s create an unix alias:
$ alias myproject='cd ~/Code/myproject && atom . && open http://localhost:3000 && rails s'
`alias` command just makes shortcut for one or more other commands. It works in OS X, Linux and other unix-like based systems.
See it in action:
Now you can just type ‘myproject’ in terminal and it will automatically:
open your project location change ~/Code/myproject to your rails project destination
open atom editor if you use sublime text, replace it with `open -a “Sublime Text”`
open http://localhost:3000 in browser you have to reload page when rails server is already running
run rails server be sure this is always last command
Note: alias command works in OS X, Linux and other unix-like based systems.
Make it permanent
If you close terminal, alias will be forgotten. To make it permanent, place the alias above into `~/.bash_profile`.
Twitter Bootstrap 3 media queries
Useful tip in case you write your own CSS code upon Twitter Bootstrap and you need those same display breakpoints, I mean CSS Media Queries:
/* XS */ @media(max-width:767px){} /* SM */ @media(min-width:768px){} /* MD */ @media(min-width:992px){} /* LG */ @media(min-width:1200px){}
Original solution here:
http://stackoverflow.com/a/18850777/923507
# TODO: bootstrap less/sass variables are better.
Fulltext search in Rails, Postgres & Heroku
If you need a database search in Rails which also works on Heroku, use Postgres and gem pg_search:
https://github.com/Casecommons/pg_search
You will be able to search like this:
@projects = Project.search_by_name “Vacation”
If you need simple search form, go here:
http://railscasts.com/episodes/37-simple-search-form
Full text search
Gemfile:
gem 'pg' gem 'pg_search'
Run bundle install.
Add pg_search_scope in your model and set the against: part - you can search against any attribute
class Project < ActiveRecord::Base include PgSearch pg_search_scope :search_by_name, against: [:first_name, :last_name], ignoring: :accents, using: { tsearch: { prefix: true} } # ... rest of file end
Note #1 about a line ‘ignoring: :accents’ - it enables searching without diacritics (searching Jose and getting José, etc.). You must enable postgres extension `accents` (it’s supported on Heroku):
rails g migration add_unaccent_extension
Edit the migration file like this:
class AddUnaccentExtension < ActiveRecord::Migration def up execute "create extension unaccent" end def down execute "drop extension unaccent" end end
Note #2 about a line ‘tsearch: { prefix: true}’ - it let’s you search “vaca” for project called “vacation”. Otherwise it would return nothing.
That’s all you need for simple full text search. For more info read pg_search README.
Easy antispam protection without using captcha
Is there any option to detect spam and don’t bother users with captcha?
Not just me, but many people just hate captcha. You know, you have to retype some crazy letters and you are not able to even read them :-) If you use Ruby on Rails you may find this little trick useful.
Solution: You can assume that SPAM robot is sending the infected form within first 10 seconds for sure. Spam robots are just scripts. They’ll open the url and fill the data at a fraction of the second.
On the other side, real human need more time to compose the message. So everything what is send within first 10 seconds after page load, must be a SPAM bot we will stop (by redirecting, see before_action in calculation_requests_controller).
app/controllers/application_controller.rb
class ApplicationController < ActionController::Base before_action :antispam session['antispam_timestamp'] ||= Time.now end end def antispam
app/controllers/calculation_requests_controller.rb
class CalculationRequestsController < ApplicationController before_filter :check_if_user_is_spam_bot, only: [:create]
def create # omitted end
private def check_if_user_is_spam_bot time_to_reservation = Time.now - session['antispam_timestamp']
if time_to_reservation < 10.seconds redirect_to new_calculation_request_url, flash: {error: 'Your activity is considered as SPAM'} end end end
Same height for elements
With Twitter bootstrap you can easily achieve grid system ie. with 2 columns in a row. But what if you need same height for each of these columns?
Here is 2-columns HTML code using Twitter Bootrap:
<div class="row"> <div class="col-sm-6"> <div class="same-height"> <img class="img-responsive" src="..."></div> <p>...</p> </div> </div>
<div class="col-sm-6"> <div class="same-height"> <img class="img-responsive" src="..."></div> <p>...</p> </div> </div> </div>
Then in app/assets/javascripts/same_height.js (create this file and it will be loaded automatically).
We need write a script that will find the most high element (with css class “same-height”) and set that height to each element with that class. Here:
$(document).bind('page:change', function() {
$('body').waitForImages(function() {
var heights = $(".same-height").map(function() { return $(this).height(); }).get(),
maxHeight = Math.max.apply(null, heights);
// $(".same-height").height(maxHeight);
$(".same-height").each(function(){ additionalHeight = parseInt( $(this).attr('data-add-height') ) || 0; $(this).height(maxHeight + additionalHeight); });
});
});
Notes:
1. Notice page:change event instead of jQuery’s document.ready. We can’t use document ready since we use Turbolinks along with our Rails project. See https://github.com/rails/turbolinks
2. Function waitForImages solves the problem with wrong height when you have image inside the div. Thanks to waitForImages the code will trigger when entirely page is ready (including images). See https://github.com/alexanderdickson/waitForImages
Ako validovať aspoň jednu has_many položku
Model App:
class App < ActiveRecord::Base validates :categories, length: { minimum: 1 } end
Teraz nám #save zlyhá, v prípade, že vo formulári pre model App nemáme vybranú aspoň jednu kategóriu (napríklad cez checkboxy).
K väčšej spokojnosti s výsledkom ešte potrebujeme upraviť defaultnú správu, ktorú validácia vracia:
“Kategórie je príliš krátky/a (min. 1 znakov)”
My však chceme hlášku:
“Je potrebné vybrať aspoň jednu kategóriu”
Pre dosiahnutie tohoto prekladu treba doplniť do locales/sk.yml nasledujúci preklad:
sk: errors: models: app: too_short: '- je potrebné vybrať aspoň jednu kategóriu'