27
Groovy и Grails быстро и обо всём

Groovy и Grails. Быстро и обо всём

Embed Size (px)

DESCRIPTION

Очень быстро о языке программирования Groovy и ещё быстрее о фрэймворке Grails.

Citation preview

Page 1: Groovy и Grails. Быстро и обо всём

Groovy и Grailsбыстро и обо всём

Page 2: Groovy и Grails. Быстро и обо всём
Page 3: Groovy и Grails. Быстро и обо всём

● Работает в JVM● Статическая и динамическая типизация● Совместим с Java и всеми библиотеками● Динамический язык● Может использоваться как скриптовый● Низкий порог вхождения● Синтаксический сахар :-)

Groovy, http://groovy.codehaus.org/

Page 4: Groovy и Grails. Быстро и обо всём

Две программы

println “Hello World” import java.io.*;

public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World"); }}

Page 5: Groovy и Grails. Быстро и обо всём

import java.io.*;import java.util.*;public class HelloWorld { public static List<Integer> kvadrat(List<Integer> x) { List<Integer> y = new ArrayList<>(x.size()); for (Integer n : x) { y.add( (int)Math.round(Math.pow(n, 2)) ); } return y; } public static void main(String[] args) { List<Integer> x = new ArrayList<>(); x.add(1); x.add(2); x.add(3); x.add(4); x.add(5); List<Integer> y = kvadrat(x); for (Integer n : y) { System.out.println(n); } }}

Page 6: Groovy и Grails. Быстро и обо всём

public static List<Integer> kvadrat(List<Integer> x) {List<Integer> y = new ArrayList<>(x.size());for (Integer n : x) {

y.add((int) Math.round(Math.pow(n, 2)));}return y;

}

List<Integer> x = new ArrayList<>();x.add(1); x.add(2); x.add(3); x.add(4); x.add(5);List<Integer> y = kvadrat(x);for (Integer n : y) {

System.out.println(n);}

Page 7: Groovy и Grails. Быстро и обо всём

// Инициализируем x в одну строчку, используем powerpublic static List<Integer> kvadrat(List<Integer> x) {

List<Integer> y = new ArrayList<>(x.size());for (Integer n : x) {

y.add(n.power(2));}return y;

}

List<Integer> x = [1, 2, 3, 4, 5];List<Integer> y = kvadrat(x);for (Integer n : y) {

System.out.println(n);}

Page 8: Groovy и Grails. Быстро и обо всём

// Используем collect. Groovy отлично работает со списками

public static List<Integer> kvadrat(List<Integer> x) {List<Integer> y = x.collect({ n -> n.power(2) });return y;

}

List<Integer> x = [1, 2, 3, 4, 5];List<Integer> y = kvadrat(x);for (Integer n : y) {

System.out.println(n);}

Page 9: Groovy и Grails. Быстро и обо всём

// Избавимся от лишних переменных. В Java мы не могли// без них обойтись, а в Groovy - запростоpublic static List<Integer> kvadrat(List<Integer> x) {

return x.collect({ n -> n.power(2) });}

List<Integer> y = kvadrat([1, 2, 3, 4, 5]);for (Integer n : y) {

System.out.println(n);}

Page 10: Groovy и Grails. Быстро и обо всём

// Грувификация: убрали типы, точки с запятыми, return.// Перешли на .each

def kvadrat(x) { x.collect { n -> n.power(2) } }

def y = kvadrat([1, 2, 3, 4, 5])y.each { n ->

System.out.println(n)}

Page 11: Groovy и Grails. Быстро и обо всём

// Теперь и переменная y лишняя :)

def kvadrat(x) { x.collect { n -> n.power(2) } }

kvadrat([1, 2, 3, 4, 5]).each { n ->System.out.println(n)

}

Page 12: Groovy и Grails. Быстро и обо всём

// Переменная n тоже, используем служебную it

def kvadrat(x) { x.collect { it.power(2) } }kvadrat([1, 2, 3, 4, 5]).each { println it }

Page 13: Groovy и Grails. Быстро и обо всём

// Метод kvadrat в общем-то тоже необязателен :)

[1, 2, 3, 4, 5].collect { it.power(2) }.each { println it }

Page 14: Groovy и Grails. Быстро и обо всём

Две программы

[1, 2, 3, 4, 5].collect { it.power(2) }.each { println it }

import java.io.*;import java.util.*;public class HelloWorld { public static List<Integer> kvadrat(List<Integer> x) { List<Integer> y = new ArrayList<>(x.size()); for (Integer n : x) { y.add( (int)Math.round(Math.pow(n, 2)) ); } return y; } public static void main(String[] args) { List<Integer> x = new ArrayList<>(); x.add(1); x.add(2); x.add(3); x.add(4); x.add(5); List<Integer> y = kvadrat(x); for (Integer n : y) { System.out.println(n); } }}

Page 15: Groovy и Grails. Быстро и обо всём

Немного метапрограммирования

final a = [1, 2, 3, 4, 5], b = [2, 3, 4, 5, 6]List.metaClass.kvadrat = { delegate.collect { it.power(2) } }println "${a.kvadrat()} ${b.kvadrat()}"

import javax.servlet.http.HttpServletRequestHttpServletRequest.metaClass.getRealIp = { delegate.getHeader('X-Real-Ip') ?: delegate.remoteAddr }

Page 16: Groovy и Grails. Быстро и обо всём

Миксины

class Eat { def eat() { println "I ate" } }class Drink { def drink() { println "I drinked" } }class Animal {}; class Mammal extends Animal {}

@Mixin(Eat) class Human extends Mammal {}

final me = new Human()me.eat()Human.mixin(Drink)me.drink()

Page 17: Groovy и Grails. Быстро и обо всём

Прокси

class Human { def eat() {} def drink() {}}final x = [ eat: { println "I ate." }, drink: { println "I drinked." } ] as Humanx.eat()println "${x.class}: ${x instanceof Human}"

I ate.class Human1_groovyProxy: true

Page 18: Groovy и Grails. Быстро и обо всём

I/O

println new File('/etc/passwd').textprintln new URL('http://baron.su/').text

import groovy.json.*def builder = new JsonBuilder()builder.human ( name: 'Vasya', height: 180 )new File('/tmp/out.json').withWriter { w -> w.println builder.toString()}{"human":{"name":"Vasya","height":180}}

Page 19: Groovy и Grails. Быстро и обо всём

POGO

class Human { def name, sex, height, weight String toString() { "$name ($sex): $height cm $weight kg" }}println new Human(name: 'Vasya', sex: 'every day', height: 180, weight: 80)

Vasya (every day): 180 cm 80 kg

Page 20: Groovy и Grails. Быстро и обо всём

GORM

class Person { String name int age static constraints = { name blank: false }}

new Person(name: ‘Ruslan’, age: 31).save(flush:true)final ruslan = Person.findOrCreateByNameAndAge(‘Ruslan’, 31).save()

Page 21: Groovy и Grails. Быстро и обо всём

GORM

● Удобная надстройка над Hibernate● Pessimistic & Optimistic locking● Мощная система валидации данных● Все возможности Hibernate доступны● Convention over Configuration

Page 22: Groovy и Grails. Быстро и обо всём

Grails

● Convention over Configuration● Самый распространённый для web● Постоянно развивается● Большое сообщество разработчиков● Поддержка плагинов

Page 23: Groovy и Grails. Быстро и обо всём

Grails. Модель

package dummyclass Password {

String username String password String url

static constraints = { }}

Page 24: Groovy и Grails. Быстро и обо всём

Grails. Контроллер

package dummy

class PasswordController { static scaffold = Password

def index() { }}

Page 25: Groovy и Grails. Быстро и обо всём

Grails. Bootstrap

import dummy.Passwordclass BootStrap {

def init = { servletContext -> new Password(username: 'admin', password: 'password', url: 'http://berserktcg.ru/').save(flush: true) } def destroy = { }}

Page 26: Groovy и Grails. Быстро и обо всём

Scaffolding

Page 27: Groovy и Grails. Быстро и обо всём

Вопросы из зала? :)