Vad ar Groovy och Grails

Loading...

Flash Player 9 (or above) is needed to view presentations.
We have detected that you do not have it on your computer. To install it, go here.

0 comments

Post a comment

    Post a comment
    Embed Video
    Edit your comment Cancel

    Favorites, Groups & Events

    Vad ar Groovy och Grails - Presentation Transcript

    1. i samarbete med
      Vad är Groovy och Grails?
      Jens Riboe
      September 2009
    2. Vem är Jens Riboe?
      Förliteolikakunder
    3. Varför?
    4. Produktivitetsförbättring
      Development Speed
      Konstruktionstidenför en webbapplikation med feature X
      Fem år sedan: 1-2 månader
      Idag: 1-2 dagar
    5. Språkutvecklingen
      MLSchemeHaskel
      Functional
      programming
      Pragmatic
      FP & OOP
      LISP
      STL & JGL
      λ-kalkyl
      Script
      Languages
      Perl
      ModulaPascalAda
      Python
      PHP
      Perl5
      Module
      Dynamic
      Languages
      SmallTalk
      Object
      Oriented
      Programming
      JavaScript
      Class
      Simula
      RubyGroovyJRubyScalaClojurePerl6
      Objective-C
      Abstract
      data type
      Java
      Subroutine
      C
      C++
      Fortran
      Cobol
      1960
      1970
      1980
      1990
      2000
      2010
    6. JVM blir en plattform för mer än Java
      Nyaspråkovanpåellerbredvid Java
      AnvänderJVM:ensomexekveringsmaskin
      Påsikttonar Java bortsåsom C gjordenär C++ kom
    7. JVM Språk
    8. Scala
      Martin Odersky
      École Polytechnique Fédérale de Lausanne (EPFL)
      2004
      Multi-paradigm
      Object-Oriented programming
      Java + Mixin och Traits
      Functional programming
      Closures och Pattern Matching
      Static typing
      Kompilatorn hittar många fel
      Extendible
      Lätt att skapa DSL
    9. JRubyochJython
      Mångascriptspråkfinnsporterade till JVM:en
      JRubyär en porteringav Ruby
      Jythonär en porteringav Python
      Ruby on Rails webbramverketvar trigger
      Skapadestortintresseför
      Rails somramverk
      Ruby somspråk
    10. ClojureochJaskel
      RenodladefunctionellaspråkpåJVM:en
      Clojureär en LISP variant
      Jaskelär en porteringavHaskel
    11. Groovy
    12. Groovy
      James Strachan
      2003
      http://radio.weblogs.com/0112098/2003/08/29.html
      Inspireradav Ruby och Python
      Den 'naturliga' vidareutvecklingenav Java
      Superset av Java
      Såsom C övergicki C++
      Egenskaper
      Dynamiskt (duck typing)
      Objektorienterat (classes)
      Funktionellt (closures)
    13. Bättreän Java
      Betydligtmindre text attskriva
      Duck typing
      Trevliganyaoperatorer
      Closures
      Groovy beans
      Groovy string
      Regex
      Categories
      Operator overloading
      Builders
      Nyalibsoch tools kommerhelatiden
    14. Ducktyping
      If it walks like a duck and it quacks like a duck, then it probably is as a duck
      Metodanrop på objekt utan krav på att tillhöra viss typ
      def min(a, b) { a <= b ? a : b }
      defaNumber = 17
      println "number: " + min(aNumber - 3, aNumber + 3)
      defaString = 'foobar'
      println "string: " + min('xx' + aString, 'aa' + aString)
      defaDate = new Date()
      println "date: " + min(aDate - 1, aDate + 1)
      number: 14
      string: aafoobar
      date: Fri Sep 04 11:20:17 CEST 2009
    15. Nullcatch operator ?.
      I stället för
      if (user != null && user.getEmail() != null) {
      domain = user.getEmail().getDomain();
      }
      räcker det med
      domain = user?.email?.domain
    16. Elvis operator ?:
      I stället för
      String h = System.getProperties.getProperty("user.home");
      dir = (home != null ? home : "/tmp");
      räcker det med
      dir = System.properties.'user.home' ?: '/tmp'
      println '-' * 20
      println "A) ${System.properties.'user.home' ?: '/tmp'}"
      println "B) ${System.properties.'user-home' ?: '/tmp'}"
      --------------------
      A) C:Usersjens
      B) /tmp
    17. Spaceship operator <=>
      I stället för
      List<Todo> todos = new ArrayList<Todo>();
      . . .
      Collections.sort(todos, new Comparator() {
      public intcompare(Object o1, Object o2) {
      if (o1 instanceofTodo && o2 instanceofTodo) {
      Todo t1 = (Todo) o1;
      Todo t2 = (Todo) o2;
      return t1.deadline.compareTo(t2.deadline);
      }
      return 0;
      }
      });
      räcker det med
      deftodos = [. . .]
      todos = todos.sort {t1, t2 -> t1.deadline <=> t2.deadline}
    18. Spread operator *.
      I stället för
      List<String> txt = new ArrayList<String>();
      for (Todo t : todos) {
      txt.add(t.getText());
      }
      System.out.println("txt = " + txt);
      räcker det med
      deftxt = todos*.text
      printlntxt
    19. List ochMap och Range
      Del avspråket
      List (java.util.*List)
      Map (java.util.*Map)
      deflst = [17, 'foo', 'bar', 'fee']
      assertlst[0] == 17
      assertlst[-2] == 'bar'
      assertlst[1..2] == ['foo', 'bar']
      def tbl = [one:1, two:2, three:3, four:4]
      assert tbl.one == 1
      assert tbl.four == 4
    20. Closures
      Anonymafunktionsblock
      def nums = (1..10)
      printlnnums
      printlnnums.collect {it * it}
      printlnnums.findAll {n -> n % 2}
      printlnnums.inject(0) {sum, n -> sum + n}
      [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
      [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
      [1, 3, 5, 7, 9]
      55
    21. GroovyBeans
      I stället för
      import java.util.Date;
      public classTodo {
      private String text;
      private Date deadline;
      public Todo(String t, Date d) {text=t; deadline=d;}
      public String getText() {return text;}
      public voidsetText(String t) {text=t;}
      public Date getDeadline() {return deadline;}
      public voidsetDeadline(Date d) {deadline=d;}
      };
      räcker det med
      classTodo {
      String text
      Date deadline
      }
    22. Användning av Groovy Beans
      def t = new Todo(deadline: new Date() + 3,
      text: 'Fix that bug')
      t.text = 'Write that Groovy script'
      deftodos = [new Todo(text:'Skip Java'),
      new Todo(text:'Hack w Groovy'),
      new Todo(text:'Web w Grails')]
      todos = todos.sort {t1,t2 -> t1.deadline <=> t2.deadline}
      printlntodos*.text.join(". ")
      Skip Java.
      Hack w Groovy.
      Web w Grails
    23. Categories
      Ett sätt att temporärt addera metoder till en klass
      def today = new Date()
      println "Today: ${today}"
      println "Today: ${today.iso8601()}"
      Today: Sat Sep 05 14:19:13 CEST 2009
      …MissingMethodException: No signature of method: java.util.Date.iso8601()…
      import java.text.SimpleDateFormat
      classFmtBoost {
      static String iso8601(Date self) {
      new SimpleDateFormat('yyyy-MM-dd').format(self)
      }
      static String getTraditional(Date self) {
      new SimpleDateFormat('d MMM yyyy').format(self)
      }
      }
      def today = new Date()
      use (FmtBoost) {
      println "Today: ${today.iso8601()}"
      println "Today: ${today.traditional}"
      }
      Today: 2009-09-05
      Today: 5 sep 2009
    24. Användning av FmtBoost
      classDoit {
      String text
      Date deadline = new Date()
      }
      deflst = [
      new Doit(text: 'Read that groovybook'),
      new Doit(text: 'Start usingbuilders'),
      new Doit(text: 'Investigategroovyxml')
      ]
      intday = 1
      lst.each {it.deadline += day++}
      use (FmtBoost) {
      lst.each {println "${it.deadline.traditional}: ${it.text}"}
      }
      6 sep 2009: Read that groovy book
      7 sep 2009: Start using builders
      8 sep 2009: Investigate groovy xml
    25. Builders
      Kombinationav closures och meta-programmering
      Inkrementellkonstruktionav composite structures
      Exempel
      XML och HTML
      Swing
      Ant
    26. Generera XML
      use(FmtBoost) {
      defbuf = new StringWriter()
      defxml = new MarkupBuilder(buf)
      xml.'doit-list' {
      lst.each {
      doit(deadline: it.deadline.iso8601(), it.text)
      }
      }
      printlnbuf
      }
      <doit-list>
      <doit deadline='2009-09-06'>Read that groovy book</doit>
      <doit deadline='2009-09-07'>Start using builders</doit>
      <doit deadline='2009-09-08'>Investigate groovy xml</doit>
      </doit-list>
    27. Processa XML
      def news(url, phrase) {
      def items = new XmlParser().parse(url).channel.item
      if (phrase) {
      items = items.grep { it.title.text().contains(phrase) }
      }
      items.collect {n -> [
      title: n.title.text() - " ",
      date: n.pubDate.text(), url: n.link.text(),
      text: n.description.text()
      ]}
      }
      <?xml version="1.0" ?>
      <rss>
      <channel>
      <title>Yahoo! News</title>
      <item>
      <title>Foxaddson-airtweets to ...</title>
      <link>http://...</link>
      <pubDate>Fri, 04 Sep 2009 02:54:51 GMT</pubDate>
      <description>Summerreruns are ...</description>
      </item>
      <item>...</item>
      <item>...</item>
      </channel>
      </rss>
    28. Result av news(url, phrase)
      def lst = news('http://rss.news.yahoo.com/rss/tech', 'Google')
      lst.each {
      it.text = it.text.replaceAll('<br clear="all"/>', '')
      it.text = it.text.replaceAll(/(<p>)|(</p>)/, '')
      it.text = it.text.replaceAll(/<a href.+</a>/, '')
      }
      lst.each {
      println "** ${it.text.substring(0,60)} ${it.date}"
      }
      ** AP - The executive who led Google Inc.'s expansion in China
      Fri, 04 Sep 2009 06:25:08 GMT
      ** AP - The final assault on a class-action settlement that wou
      Thu, 03 Sep 2009 23:30:27 GMT
    29. Groovy ökar produktiviteten
      Write less, butgainmore
      Kraftfulla verktyg
      Operators, operator-overloading, regex, categories, builders, meta-programming, groovy strings, groovybeans, . . .
      Kraftfulla bibliotek
      GAnt, Griffon, GORM, Grails, . . .
    30. Grails
    31. Grails
      Oblyg 'stöld' ochförbättringav 'Ruby on Rails'
      Convention over Configuration
      Automatisklagringavdomänobjekt
      Groovy-fieringav Spring Framework och Hibernate
      Genereringav boilerplate kod
      Scaffolding and Templating
      Byggnadsställningarochmallar
      GSP = Groovy Server Pages
      Många plug-ins
    32. Convention over Configuration
      Genomattplacera groovy klasseriolikafilkataloger, såbehandlas de påolikasätt
    33. Domain
      Hanteras av
      Hibernate & Spring
      class Person {
      String name, email, mobile
      Location location
      }
      class Location {
      String name
      String street, zip,
      city = 'Stockholm',
      country = 'Sweden'
      float latitude, longitude
      }
      Relation
      def person = Person.get(17)
      def lastName = "Riboe"
      person.email = "${person.name}@${domain}"
      person.save()
      def sthPlaces = Location.findByCity('Stockholm')
      Dynamiska DAO funktioner
    34. Controller
      http://server/BuddyMap/ajax/savePerson?personId=17&name=...
      class AjaxController {
      String JSON = 'application/json'
      def getDB = {...}
      def savePerson = {
      Person person = Person.get( params.personId )
      ...
      render(contentType:JSON, text: person as JSON)
      }
      def saveLocation = {...}
      def removePerson = {...}
      def removeLocation = {...}
      }
    35. Service
      Transaction
      jmf
      State-less SessionBean
      class NewsService {
      boolean transactional = true
      def load(url, phrase) {
      def items = new XmlParser().parse(url).channel.item
      if (phrase) {
      items = items.grep { it.title.text().contains(phrase) }
      }
      items.collect {
      [title:it.title.text(), date:it.pubDate.text(),
      url: n.link.text(), …]
      }
      }
      }
      DependencyInjection
      class NewsController {
      def newsService
      def index = { redirect(action: list) }
      def list = {
      def url = 'http://rss.news.yahoo.com/rss/'
      def news = newsService.load(url, params.phrase)
      [news: news, phrase: params.phrase,]
      }
      }
      ViewModel
    36. View (GSP)
      <%@ page contentType="text/html;charset=UTF-8" %>
      <html>
      <head>
      <title>News</title>
      <meta name="layout" content="main" />
      </head>
      <body>
      <h1>Some News</h1>
      <ul>
      <g:each in="${news}">
      <li>
      <b><a href="${it.url}">${it.title}</a></b><br/>
      <i>${it.date}</i><br/>
      ${it.text}
      </li>
      </g:each>
      </ul>
      </body>
      </html>
      ViewModel
    37. Layout (SiteMesh)
      <html>
      <head>
      <title>ToDo » <g:layoutTitle default="Welcome"/></title>
      <link rel="stylesheet"
      href="${resource(dir:'css',file:'todo.css')}" />
      <g:layoutHead />
      <g:javascript library="application" />
      </head>
      <body>
      <div>
      <div id="hd">
      <a id="logoTxt" href="<g:createLinkTo dir="/"/>">ToDo</a>
      </div>
      <div id="bd"><g:layoutBody/></div>
      <div id="ft">
      <div id="footerText">ToDo - A small Grails demo webapp</div>
      </div>
      </div>
      </body>
      </html>
    38. Resultatet
    39. Mera Info
    40. Webbapplikationer med Groovy och Grails
      Dag 1: Grundläggande Groovy
      Dag 2: Avancerad Groovy
      Dag 3: Kickstart med Grails
      Dag 4: Avancerad Grails
    41. Sammanfattning
      Groovy kommer gradvis ersätta Java
      Closures kommer att finnas i alla (moderna) språk
      Builders och meta-programmering
      Grails skapar snabbt nya webbapplikationer
      Convention over Configuration
      Spring & Hibernate
      GSP
    42. Frågor?
    43. Tack
      Jens Riboe
      0730-314040
      jens.riboe@ribomation.com
      www.ribomation.com
      blog.ribomation.com
    SlideShare Zeitgeist 2009

    + RibomationRibomation Nominate

    custom

    143 views, 0 favs, 0 embeds more stats

    This presentation (in Swedish) gives a gentle intro more

    More info about this document

    © All Rights Reserved

    Go to text version

    • Total Views 143
      • 143 on SlideShare
      • 0 from embeds
    • Comments 0
    • Favorites 0
    • Downloads 0
    Most viewed embeds

    more

    All embeds

    less

    Flagged as inappropriate Flag as inappropriate
    Flag as inappropriate

    Select your reason for flagging this presentation as inappropriate. If needed, use the feedback form to let us know more details.

    Cancel
    File a copyright complaint
    Having problems? Go to our helpdesk?