June 2011
2 posts
Rails Bad Practices #2 - using Time.now in scope
Ever wondered how to get your time-dependent scopes to act like bunch of lunatics?
do this:
class User < ActiveRecord::Base
scope :active, where(:activated_at.gt => Time.now)
end
and your list of active users will stub every time you restart your app. Cool!
Of course, this great trick can’t be achieved with this:
class User < ActiveRecord::Base
scope :active, lambda{...
Rails Bad Practices #1 - sql injection.
Sql injection is a very nice trick, however it’s really hard to achieve with Rails. This few simple lines of code allow all of your users to execute sql whatever way they want:
#app/models/user.rb
class User < ActiveRecord::Base
scope :very_clever_scope, lambda{|name_or_id| where("name = #{name_or_id} OR id=#{name_or_id}")
end
#app/controllers/users_controller.rb
class...
May 2011
2 posts
Recursively Setting Deep Hash Value - revisited
This great tip allows you to recursively set hash value - really useful thing when you have to generate complicated hash.
One gotcha that i found about this is, that after generating SuperHash instance you must remember about reseting the default value of this hash.
Consider this:
class SuperHash < Hash
def initialize
super { |h, k| h[k] = SuperHash.new }
end
end ...
RVM readline library problems?
4 steps to resolve:
1. sudo apt-get install ncurses-dev
2. cd $HOME/.rvm/src/ruby-1.9.2-p180/ext/readline
3. ruby extconf.rb — —with-readline-dir=”$HOME/.rvm/usr”
4. make install
More information:
http://beginrescueend.com/packages/readline/
April 2011
6 posts
Pow
Since most of us use macs and most of us work on few projects at the same time we really appreciate what 37signals did. Go and check out Pow project.
humans.txt
There is an interesting initiative coming from Spain. The idea is to put humans.txt file containing information about people who have contributed to building the site. More at humanstxt.org
Never run rails 3 application on ruby 1.8.7
You must update to 1.9.2. RoR3 applications on old ruby are slow. REALLY SLOW.
Incompatible character encodings with serialized...
Watchout for serialized fields in ActiveRecord. On ruby 1.9.2 strings in such fields get saved with ASCII-8BIT encoding, not with UTF-8 as you w’d expect.
Coffeescript flame.
Since we use coffeescript at netguru for some time now, we c’d sit back and relax while entire RoR community was burning in the hot fire of this flame.
Our favourite pics from the comments:
http://is.gd/HJK6sJ
http://is.gd/NZuBtX
http://is.gd/qTNFdT
http://is.gd/SeN28X
http://is.gd/CBbcJH
http://is.gd/UTSAtX
And this one pretty much sums it up:
http://is.gd/QUlhVZ
:)
Mongoid 2.0 and its new documentation →
March 2011
1 post
Beginner railscasts.
#26 - 6 min
#47 - 9 min
#48 - 10 min
#62 - 11 min
#134 - 7 min
#140 - 4 min
#152 - 9 min
#154 - 8 min
This are the numbers of Railscasts episodes that every Rails newbie should watch (obligatory for every newcommer in our company).
February 2011
1 post
Webrats http_accept method missing in Capybara.
If you are missing Webrats http_accept method after migrating from Webrat to Capybara this c’d be solution for rack based driver:
page.driver.header "Accept", "application/javascript"
January 2011
2 posts
Alternative hash syntax in Ruby 1.9 →
Shortcut for finding objects in rails console
Tired of typing User.find_by_verylongattribute_name(‘something’) into rails console? This little alias made my day:
class User < ActiveRecord::Base
def self.[](arg)
self.find_by_userlogin(arg)
end
end
Usage:
>> User['madsheep']
=> #<User id: 1, userlogin: "madsheep">
December 2010
8 posts
Saving embedded attachments with Mongoid and...
While developing our latest application, we discovered that Mongoid doesn’t save embedded objects when their parent is saved. On the GitHub page of this issue there were suggested some solutions and it appears that one posted by mcasimir works very well.
What happened to be the next problem is that with this solution comes the issue with saving attachments’ filenames. We’ve...
Thought of the day:
Each time someone thinks it’s a good idea to create model without timestamps or use habtm instead of hmt - Mighty God kills little kitten.
Transfering databases from one development machine...
http://proxylocal.com/
http://adam.heroku.com/past/2009/2/11/taps_for_easy_database_transfers/
Those two solutions can be easily combined to transfer mysql database from one development machine to another (no more nasty dump emailing/sending/sharing etc.)
On first machine:
taps server mysql://db_user:db_pass@localhost/database_name online_user online_pass -p 5000
proxylocal 5000
Last command...
ThinkingSphinx - delta field name
set_property :delta_column => 'another_delta_field'
Adding this property to sphinx indexes on your model allows you to use different field name then ‘delta’ for delta indexing - useful when two stages of your application share the same database.
FQL in Fgraph
Very simple way to use FQL in Fgraph (https://github.com/jugend/fgraph) with query caching.
require 'digest/sha1'
module FGraph
class Client
def fql(query)
@cached_query ||= {}
@cached_query[Digest::SHA1.hexdigest(query)] ||= HTTParty.get("https://api.facebook.com/method/fql.query", :query => {:query => query, :access_token => self.options[:access_token], :format =>...
Interactive Web apps - brainstorming @ Netguru
Small brainstorming about solutions to do even more interactive Web apps.
An easy way to do JavaScript - CoffeeScript...
A short introduction to new great tool which is CoffeeScript.
My .irbrc file.
This is how my irbrc file looks like:
if ENV.include?('RAILS_ENV') && !Object.const_defined?('RAILS_DEFAULT_LOGGER')
require 'logger'
RAILS_DEFAULT_LOGGER = Logger.new(STDOUT)
end
require 'rubygems'
require 'wirble'
require 'interactive_editor'
ActiveRecord::Base.logger = Logger.new(STDOUT) if Object.const_defined?('ActiveRecord')
Wirble.init
Wirble.colorize
November 2010
16 posts
Rails engines
Rails engines
Refinements in Ruby →
How to get table of ActiveRecord model instances...
>> SomeModel.connection.select_values SomeModel.send(:construct_finder_sql, :select =>:id, :limit => 20)
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
Method missing in JavaScript
Cute little plugin to emulate ruby’s method missing in JavaScript by Pat Nakajima
New application certificate
So you finally finished your work? Everything is checked and the code seems to be working? Brand your application with the “Works on my machine” logo and make sure your customers and co-workers see it.
More details.
This week’s new books in Programming | Any New... →
via HackerNews
RuPy Tuesday - Haml & Sass (SCSS) Presentation
Presentation JavaScript
A few days ago I did for my works mates a presentation about JavaScript. We discussed about pure JavaScript, and we did simple comparison between 2 selected JS frameworks - jQuery, and MooTools. It`s always nice to improve your skills. Enjoy.
Find + each = find_each →
"changing" object using iterator "each"
All of you know the “each” iterator. It goes over the array or another collection, sends it of an element to block, does some stuff with it, but the original collection remains unchanged.
Simple? Actually, it’s a bit more complicated.
Today I wrote one method and I totally didn’t realize that I was expecting “each” iterator to change the object I invoked...
Thinking Sphinx and Will Paginate issue.
Today i was hanged upon strange issue contected to the way how Thinking Sphinx uses will_paginate to calculate and show pagination links. In example above you can’t get to any of the pages above 50. Here is some explanation to this: http://freelancing-god.github.com/ts/en/advanced_config.html#large-result-sets
In my case i was missing the max_matches paramter in the search itself (sphinx...
Mixing ANDs and ORs in Sphinx
A few weeks ago I decided to improve searcher in application I’m currently working on. My goal was to improve the quality of results. In this article I would like to show the situation I’ve had and the way I achieved my goal.
Let’s assume we have a bookstore and we want the searcher not only to search for particular titles and authors, but also to suggest books for user based on...
Live style sheet editing! →
Planning for Failure - The Problem with Working... →
Failed to start searchd daemon with empty logfile.
One gotcha while starting sphinx in fresh project.
user@host:~/app/current$ rake ts:start
(in /home/webhr/app/current)
Failed to start searchd daemon. Check /home/user/app/current/log/searchd.log.
user@host:~/app/current$ searchd --pidfile --config config/sphinx/production.conf
Sphinx 0.9.9-release (r2117)
Copyright (c) 2001-2009, Andrew Aksyonoff
using config file...
October 2010
4 posts
If the object to which you delegate can be nil, you may want to use the :allow_nil option. In that case, it returns nil instead of raising a NoMethodError exception.
http://apidock.com/rails/Module/delegate
Slow model load in development mode (Thinking...
http://github.com/freelancing-god/thinking-sphinx/issues/closed#issue/90
rails_i18n.tmbundle fork by @chytreg →
Firebug lite in all browsers (including IE6):
- if Rails.env.development? %script{:type => "text/javascript", :src => "https://getfirebug.com/firebug-lite-beta.js"}
September 2010
3 posts
apotonick's hooks at master - GitHub →
via chytreg
node.js →
The new hot :)
Phusion Passenger 3.0.0 public beta 1 is out! –... →
January 2010
1 post
Rails class diagrams
Sometimes it’s hard to remember model attributes and relationships between them. Especially when you are new to the project, diagrams can be very helpful. I came across Railroad gem when I was searching for the right tool. It can generate controller diagrams with inheritance hierarchy and model diagrams with attributes and associations. Output is in the DOT language. Generated .dot files can...
December 2009
1 post
Truncate string preserving only full words (Ruby,...
Easy method to cut string to a defined length without leaving words cut in half.
Have fun using it :)