Why DataMapper?
DataMapper differentiates itself from other Ruby Object/Relational Mappers in a number of ways:
Identity Map
One row in the database should equal one object reference. Pretty simple idea. Pretty profound impact. If you run the following code in ActiveRecord you’ll see all
falseresults. Do the same in DataMapper and it’strueall the way down.1 @parent = Tree.first(:conditions => { :name => 'bob' }) 2 3 @parent.children.each do |child| 4 puts @parent.object_id == child.parent.object_id 5 endThis makes DataMapper faster and allocate less resources to get things done.
Plays Well With Others
With DataMapper you define your mappings in your model. Your data-store can develop independently of your models using Migrations.
To support data-stores which you don’t have the ability to manage yourself, it’s simply a matter of telling DataMapper where to look.
1 class Fruit 2 include DataMapper::Resource 3 4 storage_names[:default] = 'frt' # equivalent to set_table_name in AR 5 6 property :id, Serial 7 property :name, String, :field => 'col2' 8 endDataMapper only issues updates or creates for the properties it knows about. So it plays well with others. You can use it in an Integration Database without worrying that your application will be a bad actor causing trouble for all of your other processes.
Laziness Can Be A Virtue
Columns of potentially infinite length, like Text columns, are expensive in data-stores. They’re generally stored in a different place from the rest of your data. So instead of a fast sequential read from your hard-drive, your data-store has to hop around all over the place to get what it needs.
With DataMapper, these fields are treated like in-row associations by default, meaning they are loaded if and only if you access them. If you want more control you can enable or disable this feature for any column (not just text-fields) by passing a
lazyoption to your column mapping with a value oftrueorfalse.1 class Animal 2 include DataMapper::Resource 3 4 property :id, Serial 5 property :name, String 6 property :notes, Text # lazy-loads by default 7 endPlus, lazy-loading of Text property happens automatically and intelligently when working with associations. The following only issues 2 queries to load up all of the notes fields on each animal:
1 animals = Animal.all 2 animals.each do |pet| 3 pet.notes 4 endStrategic Eager Loading
DataMapper will only issue the very bare minimums of queries to your data-store that it needs to. For example, the following example will only issue 2 queries. Notice how we don’t supply any extra
:includeinformation.1 zoos = Zoo.all 2 zoos.each do |zoo| 3 # on first iteration, DM loads up all of the exhibits for all of the items in zoos 4 # in 1 query to the data-store. 5 6 zoo.exhibits.each do |exhibit| 7 # n+1 queries in other ORMs, not in DataMapper 8 puts "Zoo: #{zoo.name}, Exhibit: #{exhibit.name}" 9 end 10 endThe idea is that you aren’t going to load a set of objects and use only an association in just one of them. This should hold up pretty well against a 99% rule.
When you don’t want it to work like this, just load the item you want in it’s own set. So DataMapper thinks ahead. We like to call it “performant by default”. This feature single-handedly wipes out the “N+1 Query Problem”.
DataMapper also waits until the very last second to actually issue the query to your data-store. For example,
zoos = Zoo.allwon’t run the query until you start iterating overzoosor call one of the ‘kicker’ methods like#length. If you never do anything with the results of a query, DataMapper won’t incur the latency of talking to your data-store.All Ruby, All The Time
DataMapper goes further than most Ruby ORMs in letting you avoid writing raw query fragments yourself. It provides more helpers and a unique hash-based conditions syntax to cover more of the use-cases where issuing your own SQL would have been the only way to go.
For example, any finder option that are non-standard is considered a condition. So you can write
Zoo.all(:name => 'Dallas')and DataMapper will look for zoos with the name of ‘Dallas’.It’s just a little thing, but it’s so much nicer than writing
Zoo.find(:all, :conditions => [ 'name = ?', 'Dallas' ])and won’t incur the Ruby overhead ofZoo.find_by_name('Dallas'), nor is it more difficult to understand once the number of parameters increases.What if you need other comparisons though? Try these:
1 Zoo.first(:name => 'Galveston') 2 3 # 'gt' means greater-than. 'lt' is less-than. 4 Person.all(:age.gt => 30) 5 6 # 'gte' means greather-than-or-equal-to. 'lte' is also available 7 Person.all(:age.gte => 30) 8 9 Person.all(:name.not => 'bob') 10 11 # If the value of a pair is an Array, we do an IN-clause for you. 12 Person.all(:name.like => 'S%', :id => [ 1, 2, 3, 4, 5 ]) 13 14 # Does a NOT IN () clause for you. 15 Person.all(:name.not => [ 'bob', 'rick', 'steve' ]) 16 17 # Ordering 18 Person.all(:order => [ :age.desc ]) 19 # .asc is the defaultTo query a model by it’s associations, you can use a QueryPath:
1 Person.all(:links => [ :pets ], Person.pets.name => 'Pixel')You can even chain calls to
allorfirstto continue refining your query or search within a scope. See Finders for more information.Open Development
DataMapper sports a very accessible code-base and a welcoming community. Outside contributions and feedback are welcome and encouraged, especially constructive criticism. Go ahead, fork DataMapper, we’d love to see what you come up with!
Make your voice heard! Submit a ticket or patch, speak up on our mailing-list, chat with us on irc, write a spec, get it reviewed, ask for commit rights. It’s as easy as that to become a contributor.
Copyright Dan Kubb, Sam Smoot 2009
Web Design by Luke Matthew Sutton - Community Maintained
Comments [0]
Web側
全部Rubyで書いてあります. コントローラにSinatra, ビューにHamlを使っています. データベースへのアクセスはSQLを直接書いているので, 特にどうこうはありません. あとはグラフを描画するためにGruffを使っています.
サーバーはURLからもわかりますが, さくらさんです. データベースはMySQL. 最初はcoreserverの方でやっていましたけど, Gruffが利用するRMagickをインストールするコトができなかったので, しぶしぶ乗り換えた次第. ご迷惑をおかけしております.
バックグラウンド側
バックグラウンドはすべてErlangで書いています. 動作自体は各ユーザーさんのフォロワーを取得して, 例のスパムがいたらブロックするだけです.
ちなみにボクのマシンで動作させています. 当然Web側のデータベースともやり取りを行わなければいけない(ユーザーさんの取得, ブロック情報の更新)ので, その間はSSHを介してごちゃごちゃやっています*
Comments [0]
hdknr@debsq:~/tmp/cached_mem$ more config/environment.rb
memcache_options = {Comments [0]
ローカライズドテンプレートの使用
foo_ja.hml.erb, foo_ja_JP.html.erbと言う風にテンプレート自体を英語の元ファイルから分離させてしまうこともできます。例えば以下のようにファイルを配置します。
/app/views/blog/list.html.erb /app/views/blog/list_ja.html.erbこのケースでは日本語(jaロケール)の場合のみ、2番目のファイルが呼び出され、それ以外の時は1番目のファイルが呼び出されます。 render_partialの場合は、_foo.html.erb, _foo_ja.html.erbとすると、日本語の場合のみ_foo_ja.html.erbが呼び出されます。
Note メンテナンス性を考えるとこの機能はなるべく使わないことを推奨します。 こちらにその理由がありますのでご参照ください。なお、この日記のエントリに書かれているソースコードはすでにRuby-GetText-Package本体に取り込まれていますので無視してください。
使わない方がいいのか。
Comments [0]
count(*args)Count operates using three different approaches.
- Count all: By not passing any parameters to count, it will return a count of all the rows for the model.
- Count using column: By passing a column name to count, it will return a count of all the rows for the model with supplied column present
- Count using options will find the row count matched by the options used.
The third approach, count using options, accepts an option hash as the only parameter. The options are:
- :conditions: An SQL fragment like "administrator = 1" or [ "user_name = ?", username ]. See conditions in the intro to ActiveRecord::Base.
- :joins: Either an SQL fragment for additional joins like "LEFT JOIN comments ON comments.post_id = id" (rarely needed) or named associations in the same form used for the :include option, which will perform an INNER JOIN on the associated table(s). If the value is a string, then the records will be returned read-only since they will have attributes that do not correspond to the table‘s columns. Pass :readonly => false to override.
- :include: Named associations that should be loaded alongside using LEFT OUTER JOINs. The symbols named refer to already defined associations. When using named associations, count returns the number of DISTINCT items for the model you‘re counting. See eager loading under Associations.
- :order: An SQL fragment like "created_at DESC, name" (really only used with GROUP BY calculations).
- :group: An attribute name by which the result should be grouped. Uses the GROUP BY SQL-clause.
- :select: By default, this is * as in SELECT * FROM, but can be changed if you, for example, want to do a join but not include the joined columns.
- :distinct: Set this to true to make this a distinct calculation, such as SELECT COUNT(DISTINCT posts.id) …
- :from - By default, this is the table name of the class, but can be changed to an alternate table name (or even the name of a database view).
Examples for counting all:
Person.count # returns the total count of all peopleExamples for counting by column:
Person.count(:age) # returns the total count of all people whose age is present in databaseExamples for count with options:
Person.count(:conditions => "age > 26") Person.count(:conditions => "age > 26 AND job.salary > 60000", :include => :job) # because of the named association, it finds the DISTINCT count using LEFT OUTER JOIN. Person.count(:conditions => "age > 26 AND job.salary > 60000", :joins => "LEFT JOIN jobs on jobs.person_id = person.id") # finds the number of rows matching the conditions and joins. Person.count('id', :conditions => "age > 26") # Performs a COUNT(id) Person.count(:all, :conditions => "age > 26") # Performs a COUNT(*) (:all is an alias for '*')Note: Person.count(:all) will not work because it will use :all as the condition. Use Person.count instead.
[ show source ]
Comments [0]
hdknr@debsq:~$ sudo aptitude install ruby1.8 -y
パッケージリストを読み込んでいます... 完了
依存関係ツリーを作成しています
状態情報を読み取っています... 完了
拡張状態情報を読み込んでいます
パッケージの状態を初期化しています... 完了
タスクの記述を読み込んでいます... 完了
以下の新規パッケージがインストールされます:
libruby1.8{a} ruby1.8
更新: 0 個、新規インストール: 2 個、削除: 0 個、保留: 0 個。
1,969kB のアーカイブを取得する必要があります。展開後に 6,631kB のディスク領域が新たに消費されます。
拡張状態情報を書き込んでいます... 完了
取得:1 http://ftp.jp.debian.org squeeze/main libruby1.8 1.8.7.174-2 [1,678kB]
取得:2 http://ftp.jp.debian.org squeeze/main ruby1.8 1.8.7.174-2 [291kB]
1,969kB を 14s 秒でダウンロードしました (134kB/s)
未選択パッケージ libruby1.8 を選択しています。
(データベースを読み込んでいます ... 現在 30000 個のファイルとディレクトリがインストールされています。)
(.../libruby1.8_1.8.7.174-2_i386.deb から) libruby1.8 を展開しています...
未選択パッケージ ruby1.8 を選択しています。
(.../ruby1.8_1.8.7.174-2_i386.deb から) ruby1.8 を展開しています...
man-db のトリガを処理しています ...
libruby1.8 (1.8.7.174-2) を設定しています ...
ruby1.8 (1.8.7.174-2) を設定しています ...
パッケージリストを読み込んでいます... 完了
依存関係ツリーを作成しています
状態情報を読み取っています... 完了
拡張状態情報を読み込んでいます
パッケージの状態を初期化しています... 完了
拡張状態情報を書き込んでいます... 完了
タスクの記述を読み込んでいます... 完了
Comments [0]
hdknr@debsq:~$ sudo gem1.8 install mysql
Building native extensions. This could take a while...
ERROR: Error installing mysql:
ERROR: Failed to build gem native extension.
Comments [0]
Comments [0]