SlideShare a Scribd company logo
1 of 90
Download to read offline
merb
kicking mvc into high gear
Booth 501


I work for Engine Yard. They help fund projects like Merb and Rubinius, and allow me to spend time making DataMapper better. They rock.
what’s merb?
web framework
emphasizes efficiency
                             and hackability


Instead of emphasizing a complete, monolithic framework with everything built in for the 80-20 case, Merb emphasizes making it easy to build what you need. That doesn’t
mean we don’t want to make it easy to get started. Merb’s defaults provide the get-up-and-running feel that you get from more monolithic frameworks.
modular
improved api



We try to learn from other frameworks in Ruby and in the programming world at large. When we find something we like, we use it. When we find something we think we can
make easier to interact with, we do that.
give you as much
                            headroom as possible


Our goal is to maintain as small a footprint as possible to give your app more system resources to use.
no &:sym in merb



For instance, we don’t use Symbol#to_proc inside Merb, which is a convenience but dramatically slows down operations that use it.
slowdowns are a bug



Slowdowns are not unfortunate. They are a bug. If you notice that a commit to Merb makes it slower, file a ticket on LightHouse. We will take it seriously.
simplicity ftw
MOTTO:
no code is faster
 than no code
things you hear
developer time is
   expensive
servers are
   cheap
ergo:
efficiency doesn’t matter
you can always throw
 more hardware at it
And we at EY are happy to sell you hardware.
but what if you could
                                 have both?


What if we didn’t have to choose between developer efficiency and machine efficiency?
?



Would that be the holy grail?
no, that’s merb.
merb 0.9
based on rack



Rack is based on Python’s WSGY, which allows a web framework like Merb to interact with a bunch of web servers (like Mongrel, Thin, Ebb, Webrick, CGI, FastCGI)
class ApiHandler
                  def initialize(app)
                    @app = app
                  end

                  def call(env)
                    ...
                  end
                end

                use ApiHandler
                run Merb::Rack::Application.new
Here’s an example Rack handler.
def call(env)
                   request = Merb::Request.new
                   if request.path =~ %r{/api/(.*)}
                     [200, {“Content-Type” => “text/json”},
                       Api.get_json($1)]
                   else
                     @app.call(env)
                   end
                 end


Here’s what the call method looks like. You return a tuple of [status_code, headers, body].
router



Merb has a kick-ass router.
Merb::Router.prepare do |r|
                  r.resources :posts do |post|
                    post.resources :comments
                  end
                end


We support simple stuff, like resources or even nested resources.
Merb::Router.prepare do |r|
                  r.match(%r{/login/(.*)},
                    :user_agent => /MSIE/).
                  to(:controller => “account”,
                     :action => “login”,
                     :id => “[1]”
                end

But we also support regexen.
Merb::Router.prepare do |r|
                  r.match(%r{/login/(.*)},
                    :user_agent => /MSIE/).
                  to(:controller => “account”,
                         checks request.user_agent

                     :action => “login”,
                     :id => “[1]”
                end

Or any part of the Request object.
Merb::Router.prepare do |r|
                  r.match(%r{/login/(.*)},
                    :user_agent => /MSIE/).
                  to(:controller => “account”,
                     :action => “login”,
                     :id => “[1]”
                end

You can use any capture from your regex in #to hashes via “[capture_number]”
Merb::Router.prepare do |r|
                  r.match(%r{/login/(.*)},
                    :method => “post”).
                  to(:controller => “account”,
                     :action => “login”,
                     :id => “[1]”
                end

Here’s another example of using the Request object.
Merb::Router.prepare do |r|
  r.match(%r{/login/(.*)},
    :protocol => “http://”).
  to(:controller => “account”,
     :action => “login”,
     :id => “[1]”
end
accepts header,
                                              meet provides


Your client tells Merb what it can accept. You tell Merb what a controller can provide.
class Post < Application
                  provides :json, :yaml

                  def show
                    @post = Post[params[:id]]
                    display @post
                  end
                end

Here, you tell Merb to provide JSON and YAML. Then, you tell it to serialize the @post object into the appropriate form depending on what the client requested.
display flow
                                                                 display @foo
                                                           get content_type
                                                                                XML

                                                        Look for foo.xml.*                                                  yes   render



Here’s how Merb determines what to render given a specific parameter to display. This workflow assumes the client asked for XML.
display flow
   display @foo
 get content_type
       XML

Look for foo.xml.*

   @foo.to_xml
       no?
display flow
   display @foo
 get content_type
       XML

Look for foo.xml.*

   @foo.to_xml
default mimes



In order to make this work simply and seamlessly, we need Merb to know about a set of default mime types. Here’s the list.
Merb.add_mime_type(:all, nil, %w[*/*])
                Merb.add_mime_type(:yaml, :to_yaml,
                  %w[application/x-yaml text/yaml])
                Merb.add_mime_type(:text, :to_text,
                  %w[text/plain])
                Merb.add_mime_type(:html, :to_html,
                  %w[text/html application/xhtml+xml
                  application/html])



The first parameter is the internal name for the mime used by Merb. It is also the extension to use for a URL if you want that mime to be used (http://foo.com/index.json will
use the :json type).
Merb.add_mime_type(:xml, :to_xml,
                  %w[application/xml text/xml
                     application/x-xml],
                  :Encoding => quot;UTF-8quot;)
                Merb.add_mime_type(:js, :to_json,
                  %w[text/javascript
                     application/javascript
                     application/x-javascript])
                Merb.add_mime_type(:json, :to_json,
                  %w[application/json text/x-json])

The second parameter is an Array of mime types from the Accept header that will match the mime. The first item in the list is the mime-type that will be returned to the client.
class Post < Application
                  provides :json, :yaml, :xml

                  def show
                    @post = Post[params[:id]]
                    display @post
                  end
                end

Here’s the example again.
class Post < Application
                  provides :json, :yaml, :xml

                  def show(id)
                    @post = Post[id]
                           merb-action-args

                    display @post
                  end
                end

We can use the merb-action-args to simplify our controllers.
a benefit of modularity



Let’s take a look at an simple benefit of Merb’s modularity.
class Mail < Merb::Mailer
                   before :shared_behavior

                   def index
                     render_mail
                   end
                 end




Mailers look the same as controllers.
class Mail < Merb::Mailer
                  before :shared_behavior

                  def index
                    render_mail :foo
                  end
                end




You can pass them a symbol, which will use a different template.
class Mail < Merb::Mailer
                  before :shared_behavior

                  def index
                    render_mail :html => :foo,
                      :text => :bar
                  end
                end




You can also use special templates for html and text, without any fancy methods.
class Mail < Merb::Mailer
                  before :shared_behavior

                  def index
                    attach File.open(“/foo/bar”)
                    render_mail :html => :foo,
                      :text => :bar
                  end
                end



You can attach a file, which will automatically figure out the mime and use it.
class Mail < Merb::Mailer
                   before :shared_behavior
                   layout :mailers

                   def index
                     attach File.open(“/foo/bar”)
                     render_mail :html => :foo,
                       :text => :bar
                   end
                 end


You can use layouts, just like regular controllers.
send_mail Mail, :index,
                    {:to => “wycats@gmail.com”}




You call mailers in your controllers like this.
class Mail < Merb::Mailer
  before :shared_behavior
  layout :mailers

  def index
    attach File.open(“/foo/bar”)
    render_mail :html => :foo,
      :text => :bar
  end
end
class Mail < Merb::Mailer
                   before :shared_behavior
                   layout :mailers

                   def index
                     mail.to = [“wycats@gmail.com”]
                     attach File.open(“/foo/bar”)
                     render_mail :html => :foo,
                       :text => :bar
                   end
                 end

You also have access to the raw mailer object (a MailFactory object).
testing



What about testing?
controllers are
                        plain old ruby objects


You can test Merb objects like real Ruby objects.
instantiated with new
actions are methods
they return data
describe MyController do
                   it “returns some json” do
                     @mock = fake_request(
                       :accept => “application/json”)
                     c = MyController.new(@mock)
                     c._dispatch(:index).should ==
                       {:foo => “bar”}.to_json
                   end
                 end



This is the raw way of doing testing. You probably wouldn’t do this, and it uses a private method (_dispatch).
describe MyController do
                  it “returns some json” do
                    dispatch_to(
                      MyController,
                      :index,
                      {:foo => :bar},
                      {:accept => “application/json”}
                    )
                    @controller.body.should ==
                      {:foo => :bar}.to_json
                  end
                end
You can use Merb’s helpers as well.
describe MyController do
  it “returns some json” do
    dispatch_to(
      MyController,
      :index, controller
      {:foo => :bar},
      {:accept => “application/json”}
    )
    @controller.body.should ==
      {:foo => :bar}.to_json
  end
end
describe MyController do
  it “returns some json” do
    dispatch_to(
      MyController,
      :index,
      {:foo => action
                :bar},
      {:accept => “application/json”}
    )
    @controller.body.should ==
      {:foo => :bar}.to_json
  end
end
describe MyController do
  it “returns some json” do
    dispatch_to(
      MyController,
      :index,
      {:foo => :bar},
      {:accept params “application/json”}
                =>
    )
    @controller.body.should ==
      {:foo => :bar}.to_json
  end
end
describe MyController do
  it “returns some json” do
    dispatch_to(
      MyController,
      :index,
      {:foo => :bar},
      {:accept => “application/json”}
    )      request environment
    @controller.body.should ==
      {:foo => :bar}.to_json
  end
end
getting started
sake (edge)



The preferred way to keep up with Merb now is to use the sake tasks.
sudo gem install sake
           sake -i http://merbivore.com/merb-dev.sake
           mkdir ~/merb_sources
           cd ~/merb_sources
           sake merb:clone
           sake merb:install
           sake merb:upate # later


Do this.
gem install merb



You can also get the latest released gems from Rubyforge.
merb-gen app my_app



This is the equivalent of rails my_app.
init.rb



You’ll probably want to customize init.rb.
use_orm :datamapper
                use_test :rspec
                dependency “merb_more” # or what you need
                ... other dependencies ...
                Merb::BootLoader.before_app_loads do
                  DataMapper.setup(:salesforce, ...)
                end



Use before_app_loads for things that need to know about the structure of the framework (where your controllers/models/etc. are). The dependency method automatically
handles the appropriate time to load the plugin.
merb != Rails



We’ve had a lot of back-and-forth about things that are not the same between Merb and Rails. Here’s a list of things that you should be aware of when coming from a Rails
background.
before vs. before_filter



Controllers use before :foo instead of before_filter :foo.
provides vs. respond_to



As shown above, we use a completely different API than Rails does for deciding what mime-type to return.
:except vs. :exclude



We use before :foo, :except => :bar instead of before_filter :foo, :exclude => :bar
logger vs. merb.logger



We do not have a Kernel method for our logger. You get access to our logger by doing Merb.logger.info!
fooscontroller vs. foos



Since we don’t use const_missing to figure out where to load things, there are no naming requirements for any class. All classes are loaded at boot-time.
url_for vs. url



We do url(:resource, @resource) instead of url_for_resource(@resource).
css_include_tag :foo, :bundle => :base
                                         vs.
                          stylesheet_link_tag :foo, :bundle
                                      => :base




We use css_include_tag instead of stylesheet_link_tag. We also use js_include_tag for consistency.
mailers



As shown above, our mailers are different (and much cooler).
no rjs



We don’t use RJS. We recommend using Unobtrusive JavaScript techniques and a merb_jquery plugin along these lines is available.
mandatory render



Merb actions return strings. This provides massive additional flexibility when using actions from other methods. Our render method just returns a string, and is thus required at
the end of actions.
render returns string
render :foo



render :foo renders a template, but ...
render “foo”



render “foo” renders the string wrapped in the layout. Just “foo” renders the string itself.
render_json



render :json => :... becomes render_json :...
no render :json => ...
it’s considered a bug if



There’s a bunch of notions that are typically not considered bugs, but which we do.
it’s considered a bug
                   ★    symbol#to_proc                                            ★   non-documented
                   ★    alias_method_chain                                        ★   params
                   ★    merb gets slower                                          ★   options keys
                   ★    private api use                                           ★   returns
                   ★    public api change*                                        ★   yields

                                *without deprecation period and notice in public API changelog
alias_method_chain is ok in your app code, but it’s a bug if we use it in Merb.
thank you.
any questions?



Feel free to comment on this blog post or email me at wycats@gmail.com.
</railsconf>

More Related Content

What's hot

Bioinformatics p1-perl-introduction v2013
Bioinformatics p1-perl-introduction v2013Bioinformatics p1-perl-introduction v2013
Bioinformatics p1-perl-introduction v2013Prof. Wim Van Criekinge
 
And now you have two problems. Ruby regular expressions for fun and profit by...
And now you have two problems. Ruby regular expressions for fun and profit by...And now you have two problems. Ruby regular expressions for fun and profit by...
And now you have two problems. Ruby regular expressions for fun and profit by...Codemotion
 
8 Minutes On Rack
8 Minutes On Rack8 Minutes On Rack
8 Minutes On Rackdanwrong
 
SPL: The Missing Link in Development
SPL: The Missing Link in DevelopmentSPL: The Missing Link in Development
SPL: The Missing Link in Developmentjsmith92
 
関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐい関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐいHisateru Tanaka
 
Ruby from zero to hero
Ruby from zero to heroRuby from zero to hero
Ruby from zero to heroDiego Lemos
 
Rails2 Pr
Rails2 PrRails2 Pr
Rails2 Prxibbar
 
Doing the Refactor Dance - Making Your Puppet Modules More Modular - PuppetCo...
Doing the Refactor Dance - Making Your Puppet Modules More Modular - PuppetCo...Doing the Refactor Dance - Making Your Puppet Modules More Modular - PuppetCo...
Doing the Refactor Dance - Making Your Puppet Modules More Modular - PuppetCo...Puppet
 
Getting started with Rails (2), Season 2
Getting started with Rails (2), Season 2Getting started with Rails (2), Season 2
Getting started with Rails (2), Season 2RORLAB
 
Refactor Dance - Puppet Labs 'Best Practices'
Refactor Dance - Puppet Labs 'Best Practices'Refactor Dance - Puppet Labs 'Best Practices'
Refactor Dance - Puppet Labs 'Best Practices'Gary Larizza
 
Ruby on Rails 中級者を目指して - 大場寧子
Ruby on Rails 中級者を目指して - 大場寧子Ruby on Rails 中級者を目指して - 大場寧子
Ruby on Rails 中級者を目指して - 大場寧子Yasuko Ohba
 
perl usage at database applications
perl usage at database applicationsperl usage at database applications
perl usage at database applicationsJoe Jiang
 

What's hot (20)

Php
PhpPhp
Php
 
Bioinformatics p1-perl-introduction v2013
Bioinformatics p1-perl-introduction v2013Bioinformatics p1-perl-introduction v2013
Bioinformatics p1-perl-introduction v2013
 
And now you have two problems. Ruby regular expressions for fun and profit by...
And now you have two problems. Ruby regular expressions for fun and profit by...And now you have two problems. Ruby regular expressions for fun and profit by...
And now you have two problems. Ruby regular expressions for fun and profit by...
 
Introduction to Perl and BioPerl
Introduction to Perl and BioPerlIntroduction to Perl and BioPerl
Introduction to Perl and BioPerl
 
8 Minutes On Rack
8 Minutes On Rack8 Minutes On Rack
8 Minutes On Rack
 
Php
PhpPhp
Php
 
SPL: The Missing Link in Development
SPL: The Missing Link in DevelopmentSPL: The Missing Link in Development
SPL: The Missing Link in Development
 
関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐい関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐい
 
PHP - Introduction to PHP Functions
PHP -  Introduction to PHP FunctionsPHP -  Introduction to PHP Functions
PHP - Introduction to PHP Functions
 
Ruby from zero to hero
Ruby from zero to heroRuby from zero to hero
Ruby from zero to hero
 
Rails2 Pr
Rails2 PrRails2 Pr
Rails2 Pr
 
Perl Introduction
Perl IntroductionPerl Introduction
Perl Introduction
 
Doing the Refactor Dance - Making Your Puppet Modules More Modular - PuppetCo...
Doing the Refactor Dance - Making Your Puppet Modules More Modular - PuppetCo...Doing the Refactor Dance - Making Your Puppet Modules More Modular - PuppetCo...
Doing the Refactor Dance - Making Your Puppet Modules More Modular - PuppetCo...
 
Getting started with Rails (2), Season 2
Getting started with Rails (2), Season 2Getting started with Rails (2), Season 2
Getting started with Rails (2), Season 2
 
Refactor Dance - Puppet Labs 'Best Practices'
Refactor Dance - Puppet Labs 'Best Practices'Refactor Dance - Puppet Labs 'Best Practices'
Refactor Dance - Puppet Labs 'Best Practices'
 
Ruby on Rails 中級者を目指して - 大場寧子
Ruby on Rails 中級者を目指して - 大場寧子Ruby on Rails 中級者を目指して - 大場寧子
Ruby on Rails 中級者を目指して - 大場寧子
 
Rack Middleware
Rack MiddlewareRack Middleware
Rack Middleware
 
PHP Web Programming
PHP Web ProgrammingPHP Web Programming
PHP Web Programming
 
perl usage at database applications
perl usage at database applicationsperl usage at database applications
perl usage at database applications
 
Apache Velocity 1.6
Apache Velocity 1.6Apache Velocity 1.6
Apache Velocity 1.6
 

Viewers also liked

True capital usa & aum clean energy india executive summary
True capital usa & aum clean energy india executive summaryTrue capital usa & aum clean energy india executive summary
True capital usa & aum clean energy india executive summaryenergyvijay
 
Merb Day Keynote
Merb Day KeynoteMerb Day Keynote
Merb Day KeynoteYehuda Katz
 
German Photographer
German PhotographerGerman Photographer
German Photographerguest1f951f
 
Merb Camp Keynote
Merb Camp KeynoteMerb Camp Keynote
Merb Camp KeynoteYehuda Katz
 
Movie3555[1]
Movie3555[1]Movie3555[1]
Movie3555[1]rntb
 
Harry Pictures
Harry PicturesHarry Pictures
Harry Pictures경용 박
 
Vijay Swel Jan15th
Vijay Swel Jan15thVijay Swel Jan15th
Vijay Swel Jan15thenergyvijay
 
Renewable energy leadership condensed
Renewable energy leadership condensedRenewable energy leadership condensed
Renewable energy leadership condensedenergyvijay
 
It媒体细分和媒体关系管理
It媒体细分和媒体关系管理It媒体细分和媒体关系管理
It媒体细分和媒体关系管理Phil Ren
 
Why You Shouldn't Write OO
Why You Shouldn't Write OO Why You Shouldn't Write OO
Why You Shouldn't Write OO Yehuda Katz
 
E2 E Solution 4 Wind Park 1st Draft
E2 E Solution 4 Wind Park 1st DraftE2 E Solution 4 Wind Park 1st Draft
E2 E Solution 4 Wind Park 1st Draftenergyvijay
 
Writing Fast Client-Side Code: Lessons Learned from SproutCore
Writing Fast Client-Side Code: Lessons Learned from SproutCoreWriting Fast Client-Side Code: Lessons Learned from SproutCore
Writing Fast Client-Side Code: Lessons Learned from SproutCoreYehuda Katz
 
SproutCore: Amber
SproutCore: AmberSproutCore: Amber
SproutCore: AmberYehuda Katz
 
Sro Project Brief
Sro Project BriefSro Project Brief
Sro Project Briefenergyvijay
 
Rails 3: Dashing to the Finish
Rails 3: Dashing to the FinishRails 3: Dashing to the Finish
Rails 3: Dashing to the FinishYehuda Katz
 
Joe Zadeh, Airbnb presentation at Lean Startup SXSW, Austin
Joe Zadeh, Airbnb presentation at Lean Startup SXSW, AustinJoe Zadeh, Airbnb presentation at Lean Startup SXSW, Austin
Joe Zadeh, Airbnb presentation at Lean Startup SXSW, Austin500 Startups
 

Viewers also liked (20)

True capital usa & aum clean energy india executive summary
True capital usa & aum clean energy india executive summaryTrue capital usa & aum clean energy india executive summary
True capital usa & aum clean energy india executive summary
 
Merb Day Keynote
Merb Day KeynoteMerb Day Keynote
Merb Day Keynote
 
German Photographer
German PhotographerGerman Photographer
German Photographer
 
Que es el amor
Que es el amorQue es el amor
Que es el amor
 
Merb Camp Keynote
Merb Camp KeynoteMerb Camp Keynote
Merb Camp Keynote
 
Movie3555[1]
Movie3555[1]Movie3555[1]
Movie3555[1]
 
Harry Pictures
Harry PicturesHarry Pictures
Harry Pictures
 
Testing Merb
Testing MerbTesting Merb
Testing Merb
 
Vijay Swel Jan15th
Vijay Swel Jan15thVijay Swel Jan15th
Vijay Swel Jan15th
 
Renewable energy leadership condensed
Renewable energy leadership condensedRenewable energy leadership condensed
Renewable energy leadership condensed
 
It媒体细分和媒体关系管理
It媒体细分和媒体关系管理It媒体细分和媒体关系管理
It媒体细分和媒体关系管理
 
Why You Shouldn't Write OO
Why You Shouldn't Write OO Why You Shouldn't Write OO
Why You Shouldn't Write OO
 
E2 E Solution 4 Wind Park 1st Draft
E2 E Solution 4 Wind Park 1st DraftE2 E Solution 4 Wind Park 1st Draft
E2 E Solution 4 Wind Park 1st Draft
 
Writing Fast Client-Side Code: Lessons Learned from SproutCore
Writing Fast Client-Side Code: Lessons Learned from SproutCoreWriting Fast Client-Side Code: Lessons Learned from SproutCore
Writing Fast Client-Side Code: Lessons Learned from SproutCore
 
SproutCore: Amber
SproutCore: AmberSproutCore: Amber
SproutCore: Amber
 
Sro Project Brief
Sro Project BriefSro Project Brief
Sro Project Brief
 
Rails 3: Dashing to the Finish
Rails 3: Dashing to the FinishRails 3: Dashing to the Finish
Rails 3: Dashing to the Finish
 
Puppet and Openshift
Puppet and OpenshiftPuppet and Openshift
Puppet and Openshift
 
Thinking Evil Thoughts
Thinking Evil ThoughtsThinking Evil Thoughts
Thinking Evil Thoughts
 
Joe Zadeh, Airbnb presentation at Lean Startup SXSW, Austin
Joe Zadeh, Airbnb presentation at Lean Startup SXSW, AustinJoe Zadeh, Airbnb presentation at Lean Startup SXSW, Austin
Joe Zadeh, Airbnb presentation at Lean Startup SXSW, Austin
 

Similar to Merb

A Z Introduction To Ruby On Rails
A Z Introduction To Ruby On RailsA Z Introduction To Ruby On Rails
A Z Introduction To Ruby On Railsrailsconf
 
Ruby on Rails at PROMPT ISEL '11
Ruby on Rails at PROMPT ISEL '11Ruby on Rails at PROMPT ISEL '11
Ruby on Rails at PROMPT ISEL '11Pedro Cunha
 
Migration from Rails2 to Rails3
Migration from Rails2 to Rails3Migration from Rails2 to Rails3
Migration from Rails2 to Rails3Umair Amjad
 
TorqueBox: The beauty of Ruby with the power of JBoss. Presented at Devnexus...
TorqueBox: The beauty of Ruby with the power of JBoss.  Presented at Devnexus...TorqueBox: The beauty of Ruby with the power of JBoss.  Presented at Devnexus...
TorqueBox: The beauty of Ruby with the power of JBoss. Presented at Devnexus...bobmcwhirter
 
Rails 3 Beautiful Code
Rails 3 Beautiful CodeRails 3 Beautiful Code
Rails 3 Beautiful CodeGreggPollack
 
RoR 101: Session 2
RoR 101: Session 2RoR 101: Session 2
RoR 101: Session 2Rory Gianni
 
Building web framework with Rack
Building web framework with RackBuilding web framework with Rack
Building web framework with Racksickill
 
Intro to Ruby on Rails
Intro to Ruby on RailsIntro to Ruby on Rails
Intro to Ruby on Railselpizoch
 
Template rendering in rails
Template rendering in rails Template rendering in rails
Template rendering in rails Hung Wu Lo
 
TorqueBox - Ruby Hoedown 2011
TorqueBox - Ruby Hoedown 2011TorqueBox - Ruby Hoedown 2011
TorqueBox - Ruby Hoedown 2011Lance Ball
 
Ruby on Rails 2.1 What's New
Ruby on Rails 2.1 What's NewRuby on Rails 2.1 What's New
Ruby on Rails 2.1 What's NewLibin Pan
 
Phoenix for Rails Devs
Phoenix for Rails DevsPhoenix for Rails Devs
Phoenix for Rails DevsDiacode
 
Introduction à Ruby
Introduction à RubyIntroduction à Ruby
Introduction à RubyMicrosoft
 
Integrating Flex And Rails With Ruby Amf
Integrating Flex And Rails With Ruby AmfIntegrating Flex And Rails With Ruby Amf
Integrating Flex And Rails With Ruby Amfrailsconf
 
Carlosbrando Rubyonrails21 En
Carlosbrando Rubyonrails21 EnCarlosbrando Rubyonrails21 En
Carlosbrando Rubyonrails21 EnCasey Bradford
 
Rails web api 开发
Rails web api 开发Rails web api 开发
Rails web api 开发shaokun
 

Similar to Merb (20)

A Z Introduction To Ruby On Rails
A Z Introduction To Ruby On RailsA Z Introduction To Ruby On Rails
A Z Introduction To Ruby On Rails
 
A-Z Intro To Rails
A-Z Intro To RailsA-Z Intro To Rails
A-Z Intro To Rails
 
Ruby on Rails at PROMPT ISEL '11
Ruby on Rails at PROMPT ISEL '11Ruby on Rails at PROMPT ISEL '11
Ruby on Rails at PROMPT ISEL '11
 
Migration from Rails2 to Rails3
Migration from Rails2 to Rails3Migration from Rails2 to Rails3
Migration from Rails2 to Rails3
 
TorqueBox: The beauty of Ruby with the power of JBoss. Presented at Devnexus...
TorqueBox: The beauty of Ruby with the power of JBoss.  Presented at Devnexus...TorqueBox: The beauty of Ruby with the power of JBoss.  Presented at Devnexus...
TorqueBox: The beauty of Ruby with the power of JBoss. Presented at Devnexus...
 
Rails 3 Beautiful Code
Rails 3 Beautiful CodeRails 3 Beautiful Code
Rails 3 Beautiful Code
 
RoR 101: Session 2
RoR 101: Session 2RoR 101: Session 2
RoR 101: Session 2
 
Building web framework with Rack
Building web framework with RackBuilding web framework with Rack
Building web framework with Rack
 
Intro to Ruby on Rails
Intro to Ruby on RailsIntro to Ruby on Rails
Intro to Ruby on Rails
 
Template rendering in rails
Template rendering in rails Template rendering in rails
Template rendering in rails
 
TorqueBox - Ruby Hoedown 2011
TorqueBox - Ruby Hoedown 2011TorqueBox - Ruby Hoedown 2011
TorqueBox - Ruby Hoedown 2011
 
Ruby on Rails 2.1 What's New
Ruby on Rails 2.1 What's NewRuby on Rails 2.1 What's New
Ruby on Rails 2.1 What's New
 
Phoenix for Rails Devs
Phoenix for Rails DevsPhoenix for Rails Devs
Phoenix for Rails Devs
 
Introduction à Ruby
Introduction à RubyIntroduction à Ruby
Introduction à Ruby
 
lab4_php
lab4_phplab4_php
lab4_php
 
lab4_php
lab4_phplab4_php
lab4_php
 
Integrating Flex And Rails With Ruby Amf
Integrating Flex And Rails With Ruby AmfIntegrating Flex And Rails With Ruby Amf
Integrating Flex And Rails With Ruby Amf
 
Flex With Rubyamf
Flex With RubyamfFlex With Rubyamf
Flex With Rubyamf
 
Carlosbrando Rubyonrails21 En
Carlosbrando Rubyonrails21 EnCarlosbrando Rubyonrails21 En
Carlosbrando Rubyonrails21 En
 
Rails web api 开发
Rails web api 开发Rails web api 开发
Rails web api 开发
 

More from Yehuda Katz

Sprout core and performance
Sprout core and performanceSprout core and performance
Sprout core and performanceYehuda Katz
 
Organizing jQuery Projects Without OO
Organizing jQuery Projects Without OOOrganizing jQuery Projects Without OO
Organizing jQuery Projects Without OOYehuda Katz
 
Rails 3 overview
Rails 3 overviewRails 3 overview
Rails 3 overviewYehuda Katz
 
Making your oss project more like rails
Making your oss project more like railsMaking your oss project more like rails
Making your oss project more like railsYehuda Katz
 
Vaporware To Awesome
Vaporware To AwesomeVaporware To Awesome
Vaporware To AwesomeYehuda Katz
 
jQuery and Ruby Web Frameworks
jQuery and Ruby Web FrameworksjQuery and Ruby Web Frameworks
jQuery and Ruby Web FrameworksYehuda Katz
 
jQuery Presentation to Rails Developers
jQuery Presentation to Rails DevelopersjQuery Presentation to Rails Developers
jQuery Presentation to Rails DevelopersYehuda Katz
 

More from Yehuda Katz (8)

Sprout core and performance
Sprout core and performanceSprout core and performance
Sprout core and performance
 
Organizing jQuery Projects Without OO
Organizing jQuery Projects Without OOOrganizing jQuery Projects Without OO
Organizing jQuery Projects Without OO
 
Rails 3 overview
Rails 3 overviewRails 3 overview
Rails 3 overview
 
Making your oss project more like rails
Making your oss project more like railsMaking your oss project more like rails
Making your oss project more like rails
 
Vaporware To Awesome
Vaporware To AwesomeVaporware To Awesome
Vaporware To Awesome
 
Merb jQuery
Merb jQueryMerb jQuery
Merb jQuery
 
jQuery and Ruby Web Frameworks
jQuery and Ruby Web FrameworksjQuery and Ruby Web Frameworks
jQuery and Ruby Web Frameworks
 
jQuery Presentation to Rails Developers
jQuery Presentation to Rails DevelopersjQuery Presentation to Rails Developers
jQuery Presentation to Rails Developers
 

Recently uploaded

DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 

Recently uploaded (20)

DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 

Merb

  • 2. Booth 501 I work for Engine Yard. They help fund projects like Merb and Rubinius, and allow me to spend time making DataMapper better. They rock.
  • 5. emphasizes efficiency and hackability Instead of emphasizing a complete, monolithic framework with everything built in for the 80-20 case, Merb emphasizes making it easy to build what you need. That doesn’t mean we don’t want to make it easy to get started. Merb’s defaults provide the get-up-and-running feel that you get from more monolithic frameworks.
  • 7. improved api We try to learn from other frameworks in Ruby and in the programming world at large. When we find something we like, we use it. When we find something we think we can make easier to interact with, we do that.
  • 8. give you as much headroom as possible Our goal is to maintain as small a footprint as possible to give your app more system resources to use.
  • 9. no &:sym in merb For instance, we don’t use Symbol#to_proc inside Merb, which is a convenience but dramatically slows down operations that use it.
  • 10. slowdowns are a bug Slowdowns are not unfortunate. They are a bug. If you notice that a commit to Merb makes it slower, file a ticket on LightHouse. We will take it seriously.
  • 12. MOTTO: no code is faster than no code
  • 14. developer time is expensive
  • 15. servers are cheap
  • 17. you can always throw more hardware at it
  • 18. And we at EY are happy to sell you hardware.
  • 19. but what if you could have both? What if we didn’t have to choose between developer efficiency and machine efficiency?
  • 20. ? Would that be the holy grail?
  • 23. based on rack Rack is based on Python’s WSGY, which allows a web framework like Merb to interact with a bunch of web servers (like Mongrel, Thin, Ebb, Webrick, CGI, FastCGI)
  • 24. class ApiHandler def initialize(app) @app = app end def call(env) ... end end use ApiHandler run Merb::Rack::Application.new Here’s an example Rack handler.
  • 25. def call(env) request = Merb::Request.new if request.path =~ %r{/api/(.*)} [200, {“Content-Type” => “text/json”}, Api.get_json($1)] else @app.call(env) end end Here’s what the call method looks like. You return a tuple of [status_code, headers, body].
  • 26. router Merb has a kick-ass router.
  • 27. Merb::Router.prepare do |r| r.resources :posts do |post| post.resources :comments end end We support simple stuff, like resources or even nested resources.
  • 28. Merb::Router.prepare do |r| r.match(%r{/login/(.*)}, :user_agent => /MSIE/). to(:controller => “account”, :action => “login”, :id => “[1]” end But we also support regexen.
  • 29. Merb::Router.prepare do |r| r.match(%r{/login/(.*)}, :user_agent => /MSIE/). to(:controller => “account”, checks request.user_agent :action => “login”, :id => “[1]” end Or any part of the Request object.
  • 30. Merb::Router.prepare do |r| r.match(%r{/login/(.*)}, :user_agent => /MSIE/). to(:controller => “account”, :action => “login”, :id => “[1]” end You can use any capture from your regex in #to hashes via “[capture_number]”
  • 31. Merb::Router.prepare do |r| r.match(%r{/login/(.*)}, :method => “post”). to(:controller => “account”, :action => “login”, :id => “[1]” end Here’s another example of using the Request object.
  • 32. Merb::Router.prepare do |r| r.match(%r{/login/(.*)}, :protocol => “http://”). to(:controller => “account”, :action => “login”, :id => “[1]” end
  • 33. accepts header, meet provides Your client tells Merb what it can accept. You tell Merb what a controller can provide.
  • 34. class Post < Application provides :json, :yaml def show @post = Post[params[:id]] display @post end end Here, you tell Merb to provide JSON and YAML. Then, you tell it to serialize the @post object into the appropriate form depending on what the client requested.
  • 35. display flow display @foo get content_type XML Look for foo.xml.* yes render Here’s how Merb determines what to render given a specific parameter to display. This workflow assumes the client asked for XML.
  • 36. display flow display @foo get content_type XML Look for foo.xml.* @foo.to_xml no?
  • 37. display flow display @foo get content_type XML Look for foo.xml.* @foo.to_xml
  • 38. default mimes In order to make this work simply and seamlessly, we need Merb to know about a set of default mime types. Here’s the list.
  • 39. Merb.add_mime_type(:all, nil, %w[*/*]) Merb.add_mime_type(:yaml, :to_yaml, %w[application/x-yaml text/yaml]) Merb.add_mime_type(:text, :to_text, %w[text/plain]) Merb.add_mime_type(:html, :to_html, %w[text/html application/xhtml+xml application/html]) The first parameter is the internal name for the mime used by Merb. It is also the extension to use for a URL if you want that mime to be used (http://foo.com/index.json will use the :json type).
  • 40. Merb.add_mime_type(:xml, :to_xml, %w[application/xml text/xml application/x-xml], :Encoding => quot;UTF-8quot;) Merb.add_mime_type(:js, :to_json, %w[text/javascript application/javascript application/x-javascript]) Merb.add_mime_type(:json, :to_json, %w[application/json text/x-json]) The second parameter is an Array of mime types from the Accept header that will match the mime. The first item in the list is the mime-type that will be returned to the client.
  • 41. class Post < Application provides :json, :yaml, :xml def show @post = Post[params[:id]] display @post end end Here’s the example again.
  • 42. class Post < Application provides :json, :yaml, :xml def show(id) @post = Post[id] merb-action-args display @post end end We can use the merb-action-args to simplify our controllers.
  • 43. a benefit of modularity Let’s take a look at an simple benefit of Merb’s modularity.
  • 44. class Mail < Merb::Mailer before :shared_behavior def index render_mail end end Mailers look the same as controllers.
  • 45. class Mail < Merb::Mailer before :shared_behavior def index render_mail :foo end end You can pass them a symbol, which will use a different template.
  • 46. class Mail < Merb::Mailer before :shared_behavior def index render_mail :html => :foo, :text => :bar end end You can also use special templates for html and text, without any fancy methods.
  • 47. class Mail < Merb::Mailer before :shared_behavior def index attach File.open(“/foo/bar”) render_mail :html => :foo, :text => :bar end end You can attach a file, which will automatically figure out the mime and use it.
  • 48. class Mail < Merb::Mailer before :shared_behavior layout :mailers def index attach File.open(“/foo/bar”) render_mail :html => :foo, :text => :bar end end You can use layouts, just like regular controllers.
  • 49. send_mail Mail, :index, {:to => “wycats@gmail.com”} You call mailers in your controllers like this.
  • 50. class Mail < Merb::Mailer before :shared_behavior layout :mailers def index attach File.open(“/foo/bar”) render_mail :html => :foo, :text => :bar end end
  • 51. class Mail < Merb::Mailer before :shared_behavior layout :mailers def index mail.to = [“wycats@gmail.com”] attach File.open(“/foo/bar”) render_mail :html => :foo, :text => :bar end end You also have access to the raw mailer object (a MailFactory object).
  • 53. controllers are plain old ruby objects You can test Merb objects like real Ruby objects.
  • 57. describe MyController do it “returns some json” do @mock = fake_request( :accept => “application/json”) c = MyController.new(@mock) c._dispatch(:index).should == {:foo => “bar”}.to_json end end This is the raw way of doing testing. You probably wouldn’t do this, and it uses a private method (_dispatch).
  • 58. describe MyController do it “returns some json” do dispatch_to( MyController, :index, {:foo => :bar}, {:accept => “application/json”} ) @controller.body.should == {:foo => :bar}.to_json end end You can use Merb’s helpers as well.
  • 59. describe MyController do it “returns some json” do dispatch_to( MyController, :index, controller {:foo => :bar}, {:accept => “application/json”} ) @controller.body.should == {:foo => :bar}.to_json end end
  • 60. describe MyController do it “returns some json” do dispatch_to( MyController, :index, {:foo => action :bar}, {:accept => “application/json”} ) @controller.body.should == {:foo => :bar}.to_json end end
  • 61. describe MyController do it “returns some json” do dispatch_to( MyController, :index, {:foo => :bar}, {:accept params “application/json”} => ) @controller.body.should == {:foo => :bar}.to_json end end
  • 62. describe MyController do it “returns some json” do dispatch_to( MyController, :index, {:foo => :bar}, {:accept => “application/json”} ) request environment @controller.body.should == {:foo => :bar}.to_json end end
  • 64. sake (edge) The preferred way to keep up with Merb now is to use the sake tasks.
  • 65. sudo gem install sake sake -i http://merbivore.com/merb-dev.sake mkdir ~/merb_sources cd ~/merb_sources sake merb:clone sake merb:install sake merb:upate # later Do this.
  • 66. gem install merb You can also get the latest released gems from Rubyforge.
  • 67. merb-gen app my_app This is the equivalent of rails my_app.
  • 68. init.rb You’ll probably want to customize init.rb.
  • 69. use_orm :datamapper use_test :rspec dependency “merb_more” # or what you need ... other dependencies ... Merb::BootLoader.before_app_loads do DataMapper.setup(:salesforce, ...) end Use before_app_loads for things that need to know about the structure of the framework (where your controllers/models/etc. are). The dependency method automatically handles the appropriate time to load the plugin.
  • 70. merb != Rails We’ve had a lot of back-and-forth about things that are not the same between Merb and Rails. Here’s a list of things that you should be aware of when coming from a Rails background.
  • 71. before vs. before_filter Controllers use before :foo instead of before_filter :foo.
  • 72. provides vs. respond_to As shown above, we use a completely different API than Rails does for deciding what mime-type to return.
  • 73. :except vs. :exclude We use before :foo, :except => :bar instead of before_filter :foo, :exclude => :bar
  • 74. logger vs. merb.logger We do not have a Kernel method for our logger. You get access to our logger by doing Merb.logger.info!
  • 75. fooscontroller vs. foos Since we don’t use const_missing to figure out where to load things, there are no naming requirements for any class. All classes are loaded at boot-time.
  • 76. url_for vs. url We do url(:resource, @resource) instead of url_for_resource(@resource).
  • 77. css_include_tag :foo, :bundle => :base vs. stylesheet_link_tag :foo, :bundle => :base We use css_include_tag instead of stylesheet_link_tag. We also use js_include_tag for consistency.
  • 78. mailers As shown above, our mailers are different (and much cooler).
  • 79. no rjs We don’t use RJS. We recommend using Unobtrusive JavaScript techniques and a merb_jquery plugin along these lines is available.
  • 80. mandatory render Merb actions return strings. This provides massive additional flexibility when using actions from other methods. Our render method just returns a string, and is thus required at the end of actions.
  • 82. render :foo render :foo renders a template, but ...
  • 83. render “foo” render “foo” renders the string wrapped in the layout. Just “foo” renders the string itself.
  • 84. render_json render :json => :... becomes render_json :...
  • 86. it’s considered a bug if There’s a bunch of notions that are typically not considered bugs, but which we do.
  • 87. it’s considered a bug ★ symbol#to_proc ★ non-documented ★ alias_method_chain ★ params ★ merb gets slower ★ options keys ★ private api use ★ returns ★ public api change* ★ yields *without deprecation period and notice in public API changelog alias_method_chain is ok in your app code, but it’s a bug if we use it in Merb.
  • 89. any questions? Feel free to comment on this blog post or email me at wycats@gmail.com.