Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
Why You Should Never Use an ORM
Search
John Nunemaker
PRO
May 17, 2011
Programming
54
9.1k
Why You Should Never Use an ORM
My presentation at RailsConf 2011 on thinking about your interface, your data and your code.
John Nunemaker
PRO
May 17, 2011
Tweet
Share
More Decks by John Nunemaker
See All by John Nunemaker
Atom
jnunemaker
PRO
9
4.1k
MongoDB for Analytics
jnunemaker
PRO
10
800
Addicted to Stable
jnunemaker
PRO
32
2.4k
MongoDB for Analytics
jnunemaker
PRO
21
2.2k
MongoDB for Analytics
jnunemaker
PRO
16
30k
Why NoSQL?
jnunemaker
PRO
10
890
Don't Repeat Yourself, Repeat Others
jnunemaker
PRO
7
3.3k
I Have No Talent
jnunemaker
PRO
14
920
Why MongoDB Is Awesome
jnunemaker
PRO
18
4.3k
Other Decks in Programming
See All in Programming
Creating a Free Video Ad Network on the Edge
mizoguchicoji
0
110
どうして僕の作ったクラスが手続き型と言われなきゃいけないんですか
akikogoto
1
120
AWS Lambdaから始まった Serverlessの「熱」とキャリアパス / It started with AWS Lambda Serverless “fever” and career path
seike460
PRO
1
250
TypeScriptでライブラリとの依存を限定的にする方法
tutinoko
2
650
タクシーアプリ『GO』のリアルタイムデータ分析基盤における機械学習サービスの活用
mot_techtalk
4
1.3k
よくできたテンプレート言語として TypeScript + JSX を利用する試み / Using TypeScript + JSX outside of Web Frontend #TSKaigiKansai
izumin5210
5
1.7k
Outline View in SwiftUI
1024jp
1
320
レガシーシステムにどう立ち向かうか 複雑さと理想と現実/vs-legacy
suzukihoge
14
2.2k
シェーダーで魅せるMapLibreの動的ラスタータイル
satoshi7190
1
480
受け取る人から提供する人になるということ
little_rubyist
0
230
Click-free releases & the making of a CLI app
oheyadam
2
110
リアーキテクチャxDDD 1年間の取り組みと進化
hsawaji
1
210
Featured
See All Featured
Navigating Team Friction
lara
183
14k
Bash Introduction
62gerente
608
210k
Fireside Chat
paigeccino
34
3k
Making the Leap to Tech Lead
cromwellryan
133
8.9k
It's Worth the Effort
3n
183
27k
A Modern Web Designer's Workflow
chriscoyier
693
190k
VelocityConf: Rendering Performance Case Studies
addyosmani
325
24k
Designing the Hi-DPI Web
ddemaree
280
34k
Build your cross-platform service in a week with App Engine
jlugia
229
18k
BBQ
matthewcrist
85
9.3k
A Tale of Four Properties
chriscoyier
156
23k
The Straight Up "How To Draw Better" Workshop
denniskardys
232
140k
Transcript
Ordered List @jnunemaker RailsConf Baltimore, MD May 17, 2011 Why
You Should Never Use an ORM
You crazy man...
None
“ Albert Einstein Any intelligent fool can make things bigger,
more complex, and more violent.
Violence My Path Of
@gem
HTTParty
HappyMapper
MongoMapper
ToyStore
None
None
Three Points
1) Interface Think About Your
1) Interface Think About Your 2) Data
1) Interface Think About Your 2) Data 3) Code
Your Interface Think About
“ John Nunemaker ORMs too often lead to interface laziness.
site.memberships.create({ :user_id => user.id, :owner => true, })
site.add_owner(user)
membership.update_attributes({ :state => 1, })
membership.update_attributes({ :state => 'maximized', })
user.maximize(site)
content.to_json({ 'a crap ton': 'of options' })
ContentPresenter.new(site, date, { :page => params['page'], }).to_json
class ContentPresenter include BasePresenter def initialize(site, date, options={}) @site, @date
= site, date @options = options end def page # ... def per_page # ... def total # ... def path # ... def prev_path # ... def next_path # ... def next_page_path # ... def prev_page_path # ... def paginated # ... def content # ...
def path # ... def prev_path # ... def next_path
# ... def next_page_path # ... def prev_page_path # ... def paginated # ... def content # ... def as_json(options = nil) { 'date' => @date.to_s, 'prev_path' => prev_path, 'next_path' => next_path, 'content' => content, 'page' => page, 'per_page' => per_page, 'total' => total, 'prev_page_path' => prev_page_path, 'next_page_path' => next_page_path, } end end
Content.paginate({ :conditions => { :site_id => site.id, :date => date,
}, :page => params['page'], :per_page => 15, })
site.content_for_date(date, { :page => params['page'], })
Your Interface Think About
Your Data Think About
“ John Nunemaker ORMs sometimes hide creative ways you can
store and retrieve your data.
Failure and Triumph A Story of
{ '_id' => 'site_id:2011-03-28', '/' => {'v' => 200, 't'
=> 'Home'}, '/about/' => {'v' => 50, 't' => 'About'}, '/foo/' => {'v' => 23, 't' => 'Foo!'}, }
You say heresy! I say use case...
None
Content.get("#{site.id}:2011-03-28")
None
write data ensure_index(site_id, date, path)
read data ensure_index(site_id, date, views)
{ '_id' => BSON::ObjectId.new, 'sid' => site_id, 'p' => '/about/',
'd' => '2011-03-28', 'v' => 50, }
NewContent.for_site_and_date(site, date)
db['c.2011.5']
db['c.2011.5'] read index write index
db['c.2011.4'] => db['c.2011.5'] read index write index
None
/about/
/this/is/my/really/long/ and/descriptive/path/and/ of/course/we/need/to/ have/a/query/string? gibberish=true&yunolikesh orturls=false#DontForgetT oHashTagIt
None
Zlib.crc32('...really long path...') 762151429
Counts Every bit
Integers
Site.create(:state => 'enabled')
class Site States = { 'enabled' => 1, 'disabled' =>
2, } end Site.create({ :state => Site::States['enabled'], })
class Site def enabled? state == States['enabled'] end def disabled?
!enabled? end end
Compression
require 'rsmaz' compressed = RSmaz.compress(str) decompressed = RSmaz.decompress(compressed)
require 'zlib' compressed = Zlib::Deflate.deflate(str) decompressed = Zlib::Inflate.inflate(compressed)
require 'msgpack' ids = [1,2,3,4,5,6,7,8,9,10] compressed = MessagePack.pack(ids) decompressed =
MessagePack.unpack(compressed)
class Stylesheet class RSmazCompressor def self.compress(str) RSmaz.compress(str) end def self.decompress(str)
RSmaz.decompress(str) end end class ZlibCompressor def self.compress(str) Zlib::Deflate.deflate(str) end def self.decompress(str) Zlib::Deflate.inflate(str) end end
Compressors = { 1 => RSmazCompressor, 2 => ZlibCompressor, }
key :compressor_id, Integer key :contents, String validates_inclusion_of :compressor_id, :within => Compressors.keys def contents value = read_attribute(:contents) compressor.decompress(value) end def compressor Compressors[compressor_id] end end
Partial Updates
site.atomic_update_attributes(attrs)
Unused Fields
Counts Where
Memory/Disk/Network
class SiteMode include Scam attr_accessor :name def password_required? id ==
2 end def item_cache? id == 1 end end
SiteMode.create({ :id => 1, :name => 'live' }) SiteMode.all #
find by id or string id pp SiteMode.find(2) pp SiteMode.find('2')
class Plan include Toy::Store store(:memory, {}) attribute(:title, String) attribute(:price, Integer)
end
class Asset plugin Joint attachment :file def page_cache(version=nil) page_cache_original page_cache_version(version)
end end
current_user.sites.map do |site| Site.get(site['id']) end
ids = current_user.sites.map do |site| site['id'] end Site.all(:_id.in => ids)
Go A Long Way A Little Ruby Can
Move
Move BigintMove
Move BigintMove MakeYouWannaMove
Move BigintMove MakeYouWannaMove DaMove
Move BigintMove MakeYouWannaMove DaMove SmoothMove
Move BigintMove MakeYouWannaMove DaMove SmoothMove NightMove
Move BigintMove MakeYouWannaMove DaMove SmoothMove NightMove DanceMove
Partition.create({ :association => :moves, :model => Move, :first_id => 1,
:writer => false, })
Partition.for_writes.model.create(...)
Partition.since(since_id, last_move_id).map do |p| send(p.association).since(since_id) end
Your Data Think About
Your Code Think About
“ No code is faster than no code.
$ bx ruby performance/reads.rb Collection#find_one 0.270231008529663 Site.first 0.69925594329834
/track - no /content - no /referrers - no /sites
- yes /users - yes
class Hit def site @site ||= begin query = {'_id'
=> site_id} options = {:fields => ['tz']} collection.find_one(query, options) end end end
write code Don’t be afraid to
read code Don’t be afraid to
fail Don’t be afraid to
Site.find(id) Site.create({ :title => 'RailsTips', }) site.update_attributes(attrs) site.to_json
Your Code Think About
“ Albert Einstein It takes a touch of genius —and
a lot of courage—to move in the opposite direction.
Ordered List Thank you!
[email protected]
John Nunemaker RailsConf Baltimore, MD
May 17, 2011 @jnunemaker