SlideShare a Scribd company logo
Rails 3 generators
By: Josh Moore
About Me

✤   Josh Moore (

    ✤   www.codingforrent.com
    ✤   twitter.com/codingforrent
    ✤   http://github.com/joshsmoore
✤   Ruby
    ✤   Watir at work
    ✤   Rails on the Google App Engine for hobby
        ✤   maintain rails_dm_datastore gem
Does anybody mind if I use
English?
Contents



✤   Why you need Rails 3 generators
✤   What is new with Rails 3 generators /thor
✤   Creating your own generator
✤   Demo
Why should you care?
The Problem
Date
The Problem


✤   You cannot deviate from the rails convection without losing
    productivity.

✤   Who uses something besides the normal rails libraries?

    ✤   ERB, ActiveRecord, Test::Unit, fixtures

    ✤   The generators are not nearly as nice as they used to be.
Are you sure this is a big deal?


✤   I use DataMapper, Haml

    ✤   Generator for views does not work

    ✤   Generator for models does not work

    ✤   Scaffold does not work
Fixing it



✤   Pretty much impossible in Rails 2

✤   You could make your own generator, but not integrated different
    names or syntax
Rails 3 goal


✤   Modularity - Easy to switch components

✤   But, the generators still produce the same objects by default

    ✤   ActiveRecord

    ✤   TestUnit

    ✤   ERB
How does Rails 3 help?


✤   Meta Generators

✤   Scaffold is now a meta generator

✤   Hooks

✤   Internals are complete new - rebuilt with Thor
How does that apply to me?




✤   Demo
Scaffold Meta Generator


✤   Actually does not generator anything, just hooks into other generators
✤   Scaffold - orm, scaffold-controller
✤   ActiveRecord - test-framework
✤   TestUnit - fixture-replacement
✤   ScaffoldController - template-engine
List of hooks

✤   test_framework        ✤   orm

✤   webrat                ✤   performance_tool

✤   resource_controller   ✤   generator

✤   template_engine       ✤   scaffold_controller

✤   integration_tool      ✤   helper
Hooks


✤   Allow one generator to invoke another generator

✤   Can control what generator is invoked

✤   Allow you to override the defaults

✤   Create custom hooks if you want to
Override the defaults

✤   For each command

    ✤   --template-engine=haml

    ✤   --orm=datamapper

✤   Change the default in config/application.rb
config.generators do |g|
  g.orm             :datamapper
  g.template_engine :haml
  g.test_framework :test_unit, :fixture_replacement
=> :factory_girl
end
Thor


✤   “Map options to a class. Simply create a class with the appropriate
    annotations and have options automatically map to functions and
    parameters.”

    ✤




✤   Plan English: Replacement for Rake and sake with a sane way to pass
    parameters, which means it makes it easy to map command line
    arguments to parameters and methods in a Ruby class
> thor app:install myname --force
> thor app -L
      class App < Thor
        map "-L" => :list


        desc "install APP_NAME", "install one of the available apps"
        method_options :force => :boolean, :alias => :string
        def install(name)
          user_alias = options[:alias]
          if options.force?
            puts "forcing deletion"
          end
            puts 'installing'
        end


        desc "list [SEARCH]", "list all of the available apps, limited by SEARCH"
        def list(search="")
          # list everything
          if search == ""
            puts "searching everything"
          else
            puts "searching for #{search}"
          end
        end
      end
Things that are hard in Rake



✤   --force - boolean parameters are harder

✤   mapping -L to the app:list action

✤   parameters mapped to Ruby types (boolean, string, number, array,
    and hash)
What does this mean for Rails
generators?

✤   Thor::Actions

    ✤   General purpose actions

✤   Rails::Generators::Actions

    ✤   actions specific to rails

✤   Application templates and Rails generators now share same API
    (Thor::Actions)
Building your own generator
There’s a generator for that

✤   rails g generator NAME

✤   creates these files

✤   haml/

    ✤   haml_generator.rb - Gets called when you execute the generator

    ✤   USAGE - Describes the generator

    ✤   templates/ - templates go here
haml_generator.rb Explained
Code

✤   Place your code in instance methods

    ✤   It has access to all arguments and options

✤   All public instance methods will be executed (probably in the order
    that the methods are defined in)

✤   Inherits from Thor::Group
haml_generator.rb Explained
Parameters


✤   Arguments and options

✤   Arguments are non-named parameters that come first

✤   Options are named parameters that come last

✤   Straight from Thor
Arguments


✤   Described at the top of your class

✤   The order they are declared is the order they will be accepted on the
    command line
Arguments Example



class HamlGenerator < Rails::Generators::NamedBase

 argument :test_arg, :type => :numeric, :banner => '<number of units>'

 argument :test_arg3, :type => :string, :required => false, :default => 'default'
Declaring Arguments

✤   :desc - Description for the argument.

✤   :required, :optional - If the argument is required or not.

✤   :type - The type of the argument, can be

    ✤   :string, :hash, :array, :numeric.

✤   :default - Default value for this argument. It cannot be required and
    have default values.

✤   :banner - String that shows the input format
Argument Rules

✤   Once an argument is declared optional all remaining arguments must
    be optional

✤   you cannot “miss” an optional argument

✤   Once an array argument is declared it will parse everything option
    after it into the array

✤   Access the value of the argument by calling its name (attr_accessor)

✤   Required by default
Options


✤   Also described at the top of your class

✤   But, the order does not matter
Option Example


class HamlGenerator < Rails::Generators::NamedBase

 class_option :test_arg, :type => :numeric, :banner => '<number of units>'

 class_option :test_arg3, :type => :string, :required => false, :default => 'default'
Declaring a class_option

✤   :desc - Description for the argument.

✤   :required, :optional - If the argument is required or not.

✤   :type - The type of the argument, can be

    ✤   :boolean, :numeric, :hash, :array, :string

✤   :default - Default value for this argument. It cannot be required and
    have default values.

✤   :banner - String that shows the input format
class_option rules



✤   use the --name-of-class-option to set the class option

✤   optional by default

✤   underscores (_) in option name become dashes (-)
Implementing Hooks


✤   simply call hook_for :<NAME>

✤   switches provided --[no|skip]-test-framework

✤   under the hood

    ✤   creates a class_option

    ✤   invokes “invoke_from_option”
Example
Questions?

More Related Content

What's hot (10)

PDF
Puppet Camp Amsterdam 2015: How To Leverage The Power of the Puppet Forge
Puppet
 
PDF
What You Need to Know About Lambdas - Jamie Allen (Typesafe)
jaxLondonConference
 
PDF
Mutation testing with the mutant gem
DonSchado
 
PDF
Power of Puppet 4
Martin Alfke
 
PPT
Apache Camel
helggeist
 
PDF
Introduction to Elm
Rogerio Chaves
 
PDF
Unit testing JavaScript using Mocha and Node
Josh Mock
 
PDF
Design Summit - Rails 4 Migration - Aaron Patterson
ManageIQ
 
ODP
Modern Perl
Marcos Rebelo
 
ODP
Um2010
Jun Furuse
 
Puppet Camp Amsterdam 2015: How To Leverage The Power of the Puppet Forge
Puppet
 
What You Need to Know About Lambdas - Jamie Allen (Typesafe)
jaxLondonConference
 
Mutation testing with the mutant gem
DonSchado
 
Power of Puppet 4
Martin Alfke
 
Apache Camel
helggeist
 
Introduction to Elm
Rogerio Chaves
 
Unit testing JavaScript using Mocha and Node
Josh Mock
 
Design Summit - Rails 4 Migration - Aaron Patterson
ManageIQ
 
Modern Perl
Marcos Rebelo
 
Um2010
Jun Furuse
 

Viewers also liked (11)

PDF
Rails01
Al Sayed Gamal
 
KEY
Ruby on Rails Training - Module 1
Mark Menard
 
PDF
Rails Text Mate Cheats
dezarrolla
 
PDF
Ruby on Rails 101
Clayton Lengel-Zigich
 
PDF
Ruby on Rails Kickstart 103 & 104
Heng-Yi Wu
 
PPTX
Rest and Rails
Chamnap Chhorn
 
PDF
Railsguide
lanlau
 
PDF
Rails 3 Beginner to Builder 2011 Week 3
Richard Schneeman
 
KEY
Introducing Command Line Applications with Ruby
Nikhil Mungel
 
PDF
Ruby on Rails 101 - Presentation Slides for a Five Day Introductory Course
peter_marklund
 
PDF
Ruby on Rails for beginners
Vysakh Sreenivasan
 
Ruby on Rails Training - Module 1
Mark Menard
 
Rails Text Mate Cheats
dezarrolla
 
Ruby on Rails 101
Clayton Lengel-Zigich
 
Ruby on Rails Kickstart 103 & 104
Heng-Yi Wu
 
Rest and Rails
Chamnap Chhorn
 
Railsguide
lanlau
 
Rails 3 Beginner to Builder 2011 Week 3
Richard Schneeman
 
Introducing Command Line Applications with Ruby
Nikhil Mungel
 
Ruby on Rails 101 - Presentation Slides for a Five Day Introductory Course
peter_marklund
 
Ruby on Rails for beginners
Vysakh Sreenivasan
 
Ad

Similar to Rails 3 generators (20)

KEY
What's new and great in Rails 3 - Matt Gauger - Milwaukee Ruby Users Group De...
Matt Gauger
 
KEY
An introduction to Rails 3
Blazing Cloud
 
PDF
Lecture #5 Introduction to rails
Evgeniy Hinyuk
 
PDF
Introduction to Rails by Evgeniy Hinyuk
Pivorak MeetUp
 
PDF
Introduction to Rails - presented by Arman Ortega
arman o
 
PDF
Ruby On Rails
Balint Erdi
 
PDF
Generators
Allan Davis
 
PDF
Frozen Rails Slides
carllerche
 
PDF
Ruby On Rails Basics
Amit Solanki
 
PPT
Rails Rookies Bootcamp - Blogger
Nathanial McConnell
 
PPT
Ruby on Rails 3 Day BC
Northwest Independent Ruby Development
 
PDF
Slides
Alex Walton
 
PPTX
Rails Engine Patterns
Andy Maleh
 
PPT
Revised Rails Engine Patterns for Montreal.rb meetup Oct 16, 2012
Andy Maleh
 
PPT
Rails
SHC
 
PPTX
Rubyonrails 120409061835-phpapp02
sagaroceanic11
 
PDF
RubyEnRails2007 - Dr Nic Williams - Keynote
Dr Nic Williams
 
PPTX
Intro to Rails Give Camp Atlanta
Jason Noble
 
PDF
PDF Ruby on Rails 3 Day BC
Northwest Independent Ruby Development
 
PDF
Rails 3 : Cool New Things
Y. Thong Kuah
 
What's new and great in Rails 3 - Matt Gauger - Milwaukee Ruby Users Group De...
Matt Gauger
 
An introduction to Rails 3
Blazing Cloud
 
Lecture #5 Introduction to rails
Evgeniy Hinyuk
 
Introduction to Rails by Evgeniy Hinyuk
Pivorak MeetUp
 
Introduction to Rails - presented by Arman Ortega
arman o
 
Ruby On Rails
Balint Erdi
 
Generators
Allan Davis
 
Frozen Rails Slides
carllerche
 
Ruby On Rails Basics
Amit Solanki
 
Rails Rookies Bootcamp - Blogger
Nathanial McConnell
 
Slides
Alex Walton
 
Rails Engine Patterns
Andy Maleh
 
Revised Rails Engine Patterns for Montreal.rb meetup Oct 16, 2012
Andy Maleh
 
Rails
SHC
 
Rubyonrails 120409061835-phpapp02
sagaroceanic11
 
RubyEnRails2007 - Dr Nic Williams - Keynote
Dr Nic Williams
 
Intro to Rails Give Camp Atlanta
Jason Noble
 
PDF Ruby on Rails 3 Day BC
Northwest Independent Ruby Development
 
Rails 3 : Cool New Things
Y. Thong Kuah
 
Ad

Recently uploaded (20)

PPTX
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
PDF
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
PDF
Log-Based Anomaly Detection: Enhancing System Reliability with Machine Learning
Mohammed BEKKOUCHE
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PDF
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
PDF
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
PDF
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
SWEBOK Guide and Software Services Engineering Education
Hironori Washizaki
 
PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
PDF
The Builder’s Playbook - 2025 State of AI Report.pdf
jeroen339954
 
PDF
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
PPTX
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
PDF
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
PDF
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
PPTX
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PDF
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
PDF
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
Log-Based Anomaly Detection: Enhancing System Reliability with Machine Learning
Mohammed BEKKOUCHE
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
SWEBOK Guide and Software Services Engineering Education
Hironori Washizaki
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
The Builder’s Playbook - 2025 State of AI Report.pdf
jeroen339954
 
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 

Rails 3 generators

  • 2. About Me ✤ Josh Moore ( ✤ www.codingforrent.com ✤ twitter.com/codingforrent ✤ http://github.com/joshsmoore ✤ Ruby ✤ Watir at work ✤ Rails on the Google App Engine for hobby ✤ maintain rails_dm_datastore gem
  • 3. Does anybody mind if I use English?
  • 4. Contents ✤ Why you need Rails 3 generators ✤ What is new with Rails 3 generators /thor ✤ Creating your own generator ✤ Demo
  • 7. The Problem ✤ You cannot deviate from the rails convection without losing productivity. ✤ Who uses something besides the normal rails libraries? ✤ ERB, ActiveRecord, Test::Unit, fixtures ✤ The generators are not nearly as nice as they used to be.
  • 8. Are you sure this is a big deal? ✤ I use DataMapper, Haml ✤ Generator for views does not work ✤ Generator for models does not work ✤ Scaffold does not work
  • 9. Fixing it ✤ Pretty much impossible in Rails 2 ✤ You could make your own generator, but not integrated different names or syntax
  • 10. Rails 3 goal ✤ Modularity - Easy to switch components ✤ But, the generators still produce the same objects by default ✤ ActiveRecord ✤ TestUnit ✤ ERB
  • 11. How does Rails 3 help? ✤ Meta Generators ✤ Scaffold is now a meta generator ✤ Hooks ✤ Internals are complete new - rebuilt with Thor
  • 12. How does that apply to me? ✤ Demo
  • 13. Scaffold Meta Generator ✤ Actually does not generator anything, just hooks into other generators ✤ Scaffold - orm, scaffold-controller ✤ ActiveRecord - test-framework ✤ TestUnit - fixture-replacement ✤ ScaffoldController - template-engine
  • 14. List of hooks ✤ test_framework ✤ orm ✤ webrat ✤ performance_tool ✤ resource_controller ✤ generator ✤ template_engine ✤ scaffold_controller ✤ integration_tool ✤ helper
  • 15. Hooks ✤ Allow one generator to invoke another generator ✤ Can control what generator is invoked ✤ Allow you to override the defaults ✤ Create custom hooks if you want to
  • 16. Override the defaults ✤ For each command ✤ --template-engine=haml ✤ --orm=datamapper ✤ Change the default in config/application.rb config.generators do |g| g.orm :datamapper g.template_engine :haml g.test_framework :test_unit, :fixture_replacement => :factory_girl end
  • 17. Thor ✤ “Map options to a class. Simply create a class with the appropriate annotations and have options automatically map to functions and parameters.” ✤ ✤ Plan English: Replacement for Rake and sake with a sane way to pass parameters, which means it makes it easy to map command line arguments to parameters and methods in a Ruby class
  • 18. > thor app:install myname --force > thor app -L class App < Thor map "-L" => :list desc "install APP_NAME", "install one of the available apps" method_options :force => :boolean, :alias => :string def install(name) user_alias = options[:alias] if options.force? puts "forcing deletion" end puts 'installing' end desc "list [SEARCH]", "list all of the available apps, limited by SEARCH" def list(search="") # list everything if search == "" puts "searching everything" else puts "searching for #{search}" end end end
  • 19. Things that are hard in Rake ✤ --force - boolean parameters are harder ✤ mapping -L to the app:list action ✤ parameters mapped to Ruby types (boolean, string, number, array, and hash)
  • 20. What does this mean for Rails generators? ✤ Thor::Actions ✤ General purpose actions ✤ Rails::Generators::Actions ✤ actions specific to rails ✤ Application templates and Rails generators now share same API (Thor::Actions)
  • 21. Building your own generator
  • 22. There’s a generator for that ✤ rails g generator NAME ✤ creates these files ✤ haml/ ✤ haml_generator.rb - Gets called when you execute the generator ✤ USAGE - Describes the generator ✤ templates/ - templates go here
  • 23. haml_generator.rb Explained Code ✤ Place your code in instance methods ✤ It has access to all arguments and options ✤ All public instance methods will be executed (probably in the order that the methods are defined in) ✤ Inherits from Thor::Group
  • 24. haml_generator.rb Explained Parameters ✤ Arguments and options ✤ Arguments are non-named parameters that come first ✤ Options are named parameters that come last ✤ Straight from Thor
  • 25. Arguments ✤ Described at the top of your class ✤ The order they are declared is the order they will be accepted on the command line
  • 26. Arguments Example class HamlGenerator < Rails::Generators::NamedBase argument :test_arg, :type => :numeric, :banner => '<number of units>' argument :test_arg3, :type => :string, :required => false, :default => 'default'
  • 27. Declaring Arguments ✤ :desc - Description for the argument. ✤ :required, :optional - If the argument is required or not. ✤ :type - The type of the argument, can be ✤ :string, :hash, :array, :numeric. ✤ :default - Default value for this argument. It cannot be required and have default values. ✤ :banner - String that shows the input format
  • 28. Argument Rules ✤ Once an argument is declared optional all remaining arguments must be optional ✤ you cannot “miss” an optional argument ✤ Once an array argument is declared it will parse everything option after it into the array ✤ Access the value of the argument by calling its name (attr_accessor) ✤ Required by default
  • 29. Options ✤ Also described at the top of your class ✤ But, the order does not matter
  • 30. Option Example class HamlGenerator < Rails::Generators::NamedBase class_option :test_arg, :type => :numeric, :banner => '<number of units>' class_option :test_arg3, :type => :string, :required => false, :default => 'default'
  • 31. Declaring a class_option ✤ :desc - Description for the argument. ✤ :required, :optional - If the argument is required or not. ✤ :type - The type of the argument, can be ✤ :boolean, :numeric, :hash, :array, :string ✤ :default - Default value for this argument. It cannot be required and have default values. ✤ :banner - String that shows the input format
  • 32. class_option rules ✤ use the --name-of-class-option to set the class option ✤ optional by default ✤ underscores (_) in option name become dashes (-)
  • 33. Implementing Hooks ✤ simply call hook_for :<NAME> ✤ switches provided --[no|skip]-test-framework ✤ under the hood ✤ creates a class_option ✤ invokes “invoke_from_option”