274 | Chapter 9: Incorporating and Extending Rails
Ambition is not an object-relational mapper (in fact, it requires ActiveRecord), but it
is a simple interface on top of an ORM. It allows us to write SQL queries as pure
Ruby. It does this using lazy evaluation??”putting off SQL queries until the last
possible moment.
To try out Ambition, we will check out the latest code and use the test console provided
with Ambition (which requires us to create a development database first):*
$ git clone git://errtheblog.com/git/ambition
$ cd ambition
$ mysql -uroot -e"create database ambition_development"
$ test/console
(...)
Available models: Admin, Company, Developer, Project, Reply, Topic, and User
>>
This is a standard irb console, from which we can interact with any of these models
as if from a Rails console. We can start off by finding users with a salary of greater
than $50,000:
>> User.select{|u| u.salary > 50_000}
=> Query object: call
Here we see lazy loading in action. Nothing has been sent to the database; instead, a
Query object has been created. Ambition relies on kicker methods to actually run the
query and return results; right now, all that we have is an object representing the query.
(This kind of object is often referred to as a promise; it has the ability to perform an
expensive calculation, but will not do so unless asked.) We can call one of the kicker
methods, map (collect), to run the query and extract the results:
>> User.
Pages:
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417