Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refactoring Model Methods in Ruby On Rails

A common idiom that my camp uses in rails is as follows:

def right_things(all_things, value)
    things = []
    for thing in all_things
       things << thing if thing.attribute == value
    end
    return things
end

how can I make this better/faster/stronger?

thx

-C

like image 975
Chris Drappier Avatar asked Dec 10 '22 21:12

Chris Drappier


2 Answers

def right_things(all_things, value)
    all_things.select{|x| x.attribute == value}
end
like image 55
Chris Doggett Avatar answered Jan 01 '23 08:01

Chris Doggett


If your things are ActiveRecord models and you only need the items selected for your current purpose, you may, if you're using Rails 2.0 (? definitely 2.1) or above, find named_scopes useful.

class Thing
  named_scope :rightness, lambda { |value| :conditions => ['attribute = ?', value] }
end

So you can say

Thing.rightness(123)

, which is (in this case) similar to

Thing.find_by_attribute(123)

in that it boils down to a SQL query, but it's more easily chainable to modify the SQL. If that's useful to you, which it may not be, of course...

like image 28
Mike Woodhouse Avatar answered Jan 01 '23 06:01

Mike Woodhouse