DEV Community

Sergio Lima
Sergio Lima

Posted on • Edited on

3 2

Reapresentando o Hello World para faastRuby - A Plataforma Serverless para Ruby e Crystal - Parte II.

alt text

Olá amigos developers! Esta é a segunda parte do artigo. Se você quer saber conceitos básicos sobre faastRuby ou ainda não se cadastrou na plataforma comece por aqui Parte I.

O que vamos criar?
Usando os comandos e a plataforma serverless faastRuby, vamos criar uma function em Ruby e disponibilizá-la rapidamente na internet.

Passo a Passo da Criação do Projeto

Login

Entre na pasta que criamos anteriormente.

$ cd faastruby
$ faastruby/> 
Enter fullscreen mode Exit fullscreen mode

Faça o login com a conta criada na Parte I deste artigo.

$ faastruby/>faastruby login       
Email: you@your-email.com
Password: ********
Login successful.
Enter fullscreen mode Exit fullscreen mode

Criando o Projeto Hello World

Agora vamos criar o projeto Hello World propriamente dito.

$ faastruby/>faastruby new-project hello-world --api
Enter fullscreen mode Exit fullscreen mode

O comando faastruby new-project irá criar a pasta hello-world com as subpastas, arquivos estáticos e functions iniciais. Você verá a mensagem abaixo

+ d ./hello-world
+ f ./hello-world/project.yml
+ f ./hello-world/secrets.yml
+ d ./hello-world/functions/root
+ f ./hello-world/functions/root/handler.rb
+ f ./hello-world/functions/root/faastruby.yml
+ d ./hello-world/functions/catch-all
+ f ./hello-world/functions/catch-all/handler.rb
+ f ./hello-world/functions/catch-all/faastruby.yml
+ d ./hello-world/public
+ f ./hello-world/public/faastruby.yml
+ f ./hello-world/.gitignore
Initialized empty Git repository in /Users/you/workspace/faastruby/hello-world/.git/
Project 'hello-world' initialized.
Now run:
$ cd hello-world
$ faastruby local

Then visit http://localhost:3000
Enter fullscreen mode Exit fullscreen mode

Entre na pasta hello-world que acabamos de criar.

$ faastruby/> cd hello-world
$ faastruby/hello-world/>
Enter fullscreen mode Exit fullscreen mode

Significado de Pastas e Arquivos

├── functions <---------------- Todas functions ficam dentro desta pasta
│   ├── catch-all <------------ Se uma function não é encontrada, esta function é executada.
│   │   ├── faastruby.yml
│   │   └── handler.rb
│   └── root <----------------- Requisições em "root path" '/' caem aqui.
│       ├── faastruby.yml <---- Configuração de arquivos estáticos.
│       └── handler.rb
├── project.yml <-------------- Arquivo de configuração do projeto.
├── public <------------------- Aqui dentro ficam arquivos estáticos.
│   └── faastruby.yml
└── secrets.yml <-------------- Seus secrets ficam aqui.
Enter fullscreen mode Exit fullscreen mode

Subindo o Servidor Local
Agora vamos subir o servidor local e verificar se nosso projeto está funcionando.

$ faastruby/hello-world/> faastruby local
Enter fullscreen mode Exit fullscreen mode

Você verá a mensagem

Puma starting in single mode...
* Version 3.12.1 (ruby 2.6.0-p0), codename: Llamas in Pajamas
* Min threads: 0, max threads: 32
* Environment: production
* Listening on tcp://0.0.0.0:3000
Use Ctrl-C to stop
2019-03-23 16:21:23 -0300 | Detecting existing functions.
---
2019-03-23 16:21:23 -0300 | Ruby functions: ["root", "catch-all"]
---
2019-03-23 16:21:23 -0300 | Crystal functions: []
---
2019-03-23 16:21:23 -0300 | Listening for changes.
---
2019-03-23 16:21:23 -0300 | faastRuby Local is ready at http://localhost:3000
Enter fullscreen mode Exit fullscreen mode

Em seguida visite o endereço: http://localhost:3000

Se tudo está funcionando bem até aqui, você verá o resultado da function root em seu browser.

{
"message": "Welcome to FaaStRuby Local! Edit the function 'root' to customize this response."
}
Enter fullscreen mode Exit fullscreen mode

Criando Sua Primeira Function

Sua primeira function será chamada hello e ela responderá no formato json com a mensagem "Hello, World!".

Importante: para criar functions, você deve estar dentro da pasta functions de seu projeto.

$ faastruby/hello-world/> cd functions
$ faastruby/hello-world/functions/>
Enter fullscreen mode Exit fullscreen mode

Use o comando faastruby new hello para criar a function hello.

$ faastruby/hello-world/functions> faastruby new hello
Enter fullscreen mode Exit fullscreen mode
+ d hello
+ d hello/spec
+ f hello/spec/spec_helper.rb
+ f hello/spec/handler_spec.rb
+ f hello/README.md
+ f hello/Gemfile
+ f hello/handler.rb
+ f hello/faastruby.yml
✔ Installing gems...
Enter fullscreen mode Exit fullscreen mode

O comando faastruby new criou pastas e arquivos iniciais específicas para sua function hello.
Vamos entrar dentro da pasta hello para implementarmos nossa solução em Ruby.

$ faastruby/hello-world/functions/> cd hello
$ faastruby/hello-world/functions/hello/>
Enter fullscreen mode Exit fullscreen mode

Faça sua function hello ficar assim:

# hello-world/functions/hello/handler.rb
require 'json'

def handler event
  render json: { 'message' => 'Hello, World!' }
end
Enter fullscreen mode Exit fullscreen mode

Temos que ajustar o teste unitário:

# hello-world/functions/hello/spec/handler_spec.rb
require 'spec_helper'
require 'handler'
require 'json'

describe '#handler' do
  let(:body) { handler(event).body }
  let(:event) {
    Event.new(
      body: nil, query_params: {},
      headers: {}, context: nil
    )
  }

  context 'when function is requested' do
    let(:response_value) {
      JSON.parse(body).values.first
    }
    it 'returns a String' do
      expect(body).to be_a(String)
    end
    it "returns 'Hello, World!'" do
      expect(response_value).to eq('Hello, World!')
    end
  end
end
Enter fullscreen mode Exit fullscreen mode

Agora precisamos incluir uma gem no arquivo Gemfile desta function. Estamos usando a gem json dentro da function hello, portanto precisamos inclui-la no Gemfile.

# hello-world/functions/hello/Gemfile
source 'https://rubygems.org'

gem 'json'

group :test do
  gem 'rspec'
  gem 'faastruby-rpc'
  gem 'faastruby'
end
Enter fullscreen mode Exit fullscreen mode

Não esqueça do bundle install

$ faastruby/hello-world/functions/hello/> bundle install
Enter fullscreen mode Exit fullscreen mode

Nossos testes estão passando?

faastruby/hello-world/functions/hello/> rspec -fd
Enter fullscreen mode Exit fullscreen mode
handler
  when function is requested
    returns 'Hello, World!'
    returns a String

Finished in 3.89 seconds (files took 0.6736 seconds to load)
2 examples, 0 failures
Enter fullscreen mode Exit fullscreen mode

Subindo o Servidor Local, Novamente

Lembre-se sempre que para subir o servidor local o comando faastruby local deverá ser usado na pasta principal do projeto.

Portanto vá para a pasta raiz do projeto, hello-world e suba o servidor.

$ faastruby/hello-world/> faastruby local
Enter fullscreen mode Exit fullscreen mode

Vamos ver o funcionamento da nossa function hello.

Visite o endereço: http://localhost:3000/hello

Você verá o resultado da function hello em seu browser.

{
"message": "Hello, World!"
}
Enter fullscreen mode Exit fullscreen mode

O Primeiro Deploy

Quando executamos o deploy do projeto para a plataforma faastRuby, as functions e arquivos estáticos vão para o Workspace.

Para fazer o deploy do projeto o comando faastruby deploy deverá ser usado na pasta principal do projeto.

Portanto certifique-se que você está na pasta hello-world e execute o deploy.

$ faastruby/hello-world/> faastruby deploy
Enter fullscreen mode Exit fullscreen mode
┌ Deploying project 'hello-world' to workspace 'hello-world-stage-8f6999'
├── [✔] Connecting to workspace 'hello-world-stage-999999'
├── [✔] Uploading static assets in 'public'
├── [✔] Deploying function from 'functions/hello'
├── [✔] Deploying function from 'functions/catch-all'
└── [✔] Deploying function from 'functions/root'
* Project URL: https://hello-world-stage-999999.tor1.faast.cloud
Enter fullscreen mode Exit fullscreen mode

Finalmente, sua function está disponível na nuvem! A sua URL será parecida com a URL a seguir.

Visite o endereço no seu browser: https://hello-world-stage-999999.tor1.faast.cloud/hello

Você verá o resultado da function hello em seu browser.

{
"message": "Hello, World!"
}
Enter fullscreen mode Exit fullscreen mode

Conclusão

  • Neste artigo aprendemos como construir um projeto em faastRuby do zero e enviar para a nuvem.
  • Aprendemos como criar uma function própria, criar testes unitários e executar a function com o servidor local.

Espero que tenham gostado do artigo!

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (1)

Collapse
 
rflosi profile image
rflosi

Muito bom! Principalmente o servidor local.

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

Retry later