rubyflare
rubyflare
Ruby Flare
96 posts
Don't wanna be here? Send us removal request.
rubyflare · 11 years ago
Text
Sort a collection by multiple attributes
To sort a collection by an attribute:
items.sort_by { |x| x.last_name }
or using this shorthand:
items.sort_by(&:name)
Now if you want to sort by multiple attributes don't resort to the spaceship operator:
items.sort { |x,y| [ x.last_name, x.first_name] <=> [y.last_name, y.first_name] }
Pass in an array of attributes to sort_by:
items.sort_by { |x| [x.last_name, x.first_name] }
Much cleaner and more expressive. Removes the redundant y side of things and gets rid of that spaceship operator!
Also, Ruby 1.9.2 introduced the sort_by! method so you can also replace your sort! methods too.
4 notes · View notes
rubyflare · 12 years ago
Link
2 notes · View notes
rubyflare · 12 years ago
Link
Your Rails application probably makes use of uniqueness validations in several key places. This validation provides for a nice user experience when duplicate records are detected but as we will see in a moment, is not enough to ensure data integrity.
What Can Go Wrong?
Let’s take a look at a...
12 notes · View notes
rubyflare · 12 years ago
Text
Hidden fields generated by fields_for helper
On a rails 2.3 project, I was implementing a form with nested attributes. The fields were contained in a table. Unfortunately, the hidden id fields for existing nested attributes were automatically inserted outside of the table code. In order to override this behaviour, you simply need to explicitly add in the hidden id field where appropriate. Rails will only automatically insert the hidden field if it doesn't exist.
0 notes
rubyflare · 12 years ago
Text
Threequals in Ruby
I've always wondered what the difference was between === and == in Ruby. This blog post by Giles Bowkett explains it well:
http://gilesbowkett.blogspot.com.au/2007/11/what-is-threequals.html
Much better to use Ruby's expressiveness I think eg,
is_a? kind_of? instance_of?
0 notes
rubyflare · 12 years ago
Text
gsub accepts a replacements hash in Ruby 1.9
Here's the original bit of code:
def clean_address_data(text) text.to_s.gsub!(/\*/, '-') text.to_s.gsub!(/@/, 'at') text.to_s.gsub!(/#/, ' ') text.to_s.gsub!(/\+/, ' ') text end
With Ruby 1.9, gsub got the ability to accept a replacements hash as the second argument. So, I refactored this method to:
def clean_address_data(text) substitutions = { '*' => '-', '@' => 'at', '#' => ' ', '+' => ' ' } text.gsub(/#{substitutions.keys}/, substitutions) end
I like this much better. Gone is the explicit return of text at the end of the method, the substitutions are clearer to see and we are now performing the one gsub for all the substitutions instead of four. If extra substitutions are required, these can easily be added. Overall, I think the intent is clearer and the code more readable.
0 notes
rubyflare · 12 years ago
Text
Pruning Git
If you need to sync your local branches and tags from the remote git repo, use the following:
git fetch --prune git fetch --prune --tags
0 notes
rubyflare · 12 years ago
Text
Modify a previous git commit
If you have forgotten to add something to your last commit, you can simply amend the previous commit:
git add [file(s)] git commit --amend
If you have forgotten to add something to a commit prior to your last commit, you can use interactive rebase:
git rebase [sha]^ --interactive # modify pick to edit of the commit to amend git add [file(s)] git commit --amend git rebase --continue
Note, the rebase command is for the commit prior to the commit you wish to change.
1 note · View note
rubyflare · 12 years ago
Text
Only push the current git branch by default
When you use git push without specifying a remote repository, the current default action will push all branches. This default will be changing in git 2.0. This behaviour is configured by the push.default option. The available values for this option are:
nothing
matching - the current default
upstream
simple - the new git 2.0 default
current
You can set/override this git configuration with:
git config --global push.default simple
The simple, current and upstream modes are for those who want to push out a just single branch, not all branches (some of which may not be ready to be pushed out yet).
Read more: http://git-scm.com/docs/git-config.html
0 notes
rubyflare · 12 years ago
Link
0 notes
rubyflare · 12 years ago
Link
0 notes
rubyflare · 12 years ago
Text
Reset DNS Cache on Lion and Mountain Lion
To reset the DNS cache on Lion and Mountain Lion, use: sudo killall -HUP mDNSResponder
0 notes
rubyflare · 12 years ago
Text
Redirect_to doesn't stop execution
For some reason I have come to believe that a redirect_to statement in a Rails controller action stops the execution of the action and performs the redirect immediately. But it doesn't. I suppose this misconception has come about because I've always put redirect_to as the last statement in an action. So this allows you to do things like this: def some_action redirect_to some_path if some_condition? object.some_method end This will always execute object.some_method whether or not some_condition is met. The value of some_condition will only affect whether the request is redirected afterwards.
1 note · View note
rubyflare · 12 years ago
Text
Generating a random number from a range
I wanted to generate a random number of hours between 1 and 23 in a factory used by some tests. Since 1..23 is significant, I wanted these numbers to be in the code to reinforce their meaning. I started with: 1+ rand(23) Then I tried: (1..23).to_a.sample But finally, I discovered this neat trick you can do with Ruby 1.9's rand method: rand(1..23) That's perfect! It clearly articulates what I want: a random number between 1 and 23.
0 notes
rubyflare · 13 years ago
Text
Use detect, not select
Here's a tip I picked up from [Red Dot Ruby Conf](reddotrubyconf.com)... When you are wanting the first match for a particular condition in an array, often what people fall into the trap of doing is pulling out all matches and then just taking the first one. For a large collection, this can result in slow performance. Here's an arbitrary example. Let's say we have a large collection and we want to find the first number divisible by 3. We might write the following: large_range = 1..1_000_000 large_range.select { |num| num % 3 == 0 }.first A better way is to use the detect method: large_range.detect { |num| num % 3 == 0 } Let's get some numbers on the performance of these two bits of code. require 'benchmark' Benchmark.bm do |x| x.report { large_range.select { |num| num % 3 == 0 }.first } x.report { large_range.detect { |num| num % 3 == 0 } } end And the results are: user system total real 0.170000 0.000000 0.170000 (0.173850) 0.000000 0.000000 0.000000 (0.000009) Clearly, detect is the winner.
0 notes
rubyflare · 13 years ago
Text
Order matters
I was tripped up by this today. The behaviour of Rails when it comes to chaining orders seemed counterintuitive to me. Here's an example... class Author [post_1, post_2] Now that's all fine, but what if I want to specify an explicit order (and I don't care what the original order was). I tried the following thinking it would override the existing order but it doesn't. author.posts.order('created_at DESC') # => [post_1, post_2] I expected it to reverse the order. What it actually did was to add the order onto the query so that the actual SQL statement looks like this: SELECT "posts".* FROM "posts" WHERE "posts"."author_id" = 2 ORDER BY created_at ASC, created_at DESC One solution is to use the reorder method: author.posts.reorder('created_at DESC') # => [post_2, post_1] This replaces out any existing ordering. In my case, I'm just going to use the reverse_order method: author.posts.reverse_order # => [post_2, post_1]
2 notes · View notes
rubyflare · 13 years ago
Text
scope vs class method
In my last post I talked about the need to use lambdas in all scopes that call an existing scope that uses a lambda. An alternative to this is to use class methods instead of scope. So instead of:
scope :active, lambda { started.unfinished }
Use this:
def self.active started.unfinished end
Now, the active class method doesn't need to know that started or unfinished scopes use a lambda.
2 notes · View notes