Advanced Rails - Building Industrial-Strength Web Apps in Record Time

(Tuis.) #1
Replacing Rails Components | 275

TheQueryobject has ato_hashand a (mostly functional)to_sqlmethod, which help
debug the SQL queries and conditions being generated:


>> User.select{|u| u.salary > 50_000}.sort_by{|u| u.name}.to_sql
=> "SELECT * FROM users WHERE users.`salary` > 50000 ORDER BY users.name"
>> User.select{|u| u.salary > 50_000}.sort_by{|u| u.name}.to_hash
=> {:order=>"users.name", :conditions=>"users.`salary` > 50000"}

There are many more features, including some syntactic sugar on the standard Ruby
Enumerable methods:


>> User.any?{|u| u.salary > 50_000}
# SELECT count(*) AS count_all FROM users WHERE (users.`salary` > 50000)
=> true

>> User.all?{|u| u.salary < 500_000}
# SELECT count(*) AS count_all FROM users
# SELECT count(*) AS count_all FROM users WHERE (users.`salary` < 500000)
=> true

Consult the Ambition blog post for an overview of all the useful methods and syntax
provided. Ambition is still under heavy development and is certainly subject to
change. At this time, the best source of documentation is the README (available
from the Git repository atgit://errtheblog.com/git/ambition), as well as the source
itself.


Og


Og (short for ObjectGraph) is yet another object-relational mapping library for
Ruby. It is part of the Nitro project, which is a web framework similar to Rails. Like
Rails, Nitro is composed of layered components. However, these components take a
different approach to solve the same problems as Rails, and so it is much harder to
use Og with Rails than with Nitro. In particular, the RailsDependenciessystem
causes many problems with file loading. We can work around these problems, but
this method should still be considered very experimental.


The Og library has less baggage than ActiveRecord, and doesn’t try to do as much,
so the code is a bit more readable. It uses “magic” just as much as ActiveRecord
does, but in a different way. Rather than defining its own set of property accessors
(as DataMapper does), Og overrides the standard Rubyattr_accessormethod to
define properties. It usesObjectSpaceto find objects that represent model classes
(based on their use of the newattr_accessoror inclusion of theOg::Modelmodule).
This means that the models can look almost exactly like plain-old Ruby objects. The
only difference is that the types of the properties must be explicitly specified, so that
they can be mapped to SQL types:


class Person
attr_accessor :first_name, String
attr_accessor :last_name, String
attr_accessor :dob, Date
end
Free download pdf