SlideShare ist ein Scribd-Unternehmen logo
1 von 25
Downloaden Sie, um offline zu lesen
Ruby w/o rails
Oleksandr Simonov
About me
• Name: Oleksandr Simonov
• Occupation: Founder and Owner of Amoniac
• Hobby: Open Source contribution
• Github: @simonoff
Why Ruby w/o Rails?
• Rails is a monolithic stone
• Rails is slow
• Rails force you to be a lazy
rails is:
• activerecord
• activemodel
• activesupport
• actionmailer
• actionpack
• actionview
• activejob
• railties
benchmark
http://www.madebymarket.com/blog/dev/ruby-web-
benchmark-report.html
Lazy Rails developer
Alternatives
• Rack
• Sinatra
• Cuba
• Grape (API)
• Reel
• Nahami
• Sequel
• ROM
WEB ORM
Advantages
• Faster then Rails
• Less time for app loading
• New knowledge
Disadvantages
• No Rails like console
• No Rails like code autoloading
• No Rails helpers
• No "Magic"
• More code
Practical section
• Download list of Finnish companies
• Insert/Update local DB
• On API call returns e-invoice address
- app
- models
- services
- workers
- config
- boot.rb
- initializers
- 01-dotenv.rb
- 02-airbrake.rb
- 03-sequel.rb
- 04-sidekiq.rb
- db
- migrations
- init.rb
- config.ru
Structure
require 'rubygems'
require 'bundler/setup'
require_relative 'init' # Application code loading
require 'sidekiq/web'
use Rack::ContentLength
use Rack::CommonLogger, ::NetvisorSpreadsheets.
logger # use own logger
use Rack::ShowExceptions
run Rack::URLMap.new('/' => ::NetvisorSpreadsheets:
:Server, '/sidekiq' =>
Sidekiq::Web)
config.ru
init.rb
# encoding: UTF-8
ENV['RACK_ENV'] ||= 'development' # default environment
require 'rubygems'
module NetvisorSpreadsheets # Singletone
extend self
attr_accessor :db
def root # helper for get application root path
@root_path ||= ::Pathname.new(::File.join(File.dirname(__FILE__))).expand_path
end
def env # helper for get environment
@env ||= ENV["RACK_ENV"] || "development"
end
def logger # helper for logger
@logger ||= ::Logger.new(self.root.join('log', "#{self.env}.log").to_s)
end
end
::NetvisorSpreadsheets.logger.level = if ::NetvisorSpreadsheets.env == 'production'
::Logger::INFO
else
::Logger::DEBUG
end
# require boot file
require self.root.join('config', 'boot.rb').to_s
$LOAD_PATH.unshift ::NetvisorSpreadsheets.root # add root path to load
path
# autoload some initializers, models, workers and services
def load_folder(*path)
::Dir.glob(::NetvisorSpreadsheets.root.join(*path)).each { |r| require
r }
end
load_folder('config', 'initializers', '**/*.rb')
load_folder('app', 'models', '**/*.rb')
load_folder('app', 'workers', '**/*.rb')
load_folder('app', 'services', '**/*.rb')
# require sinatra server code
require 'config/server'
boot.rb
source 'https://rubygems.org'
gem 'sqlite3'
gem 'dotenv'
gem 'sequel'
gem 'sinatra'
gem 'sinatra-contrib'
gem 'sidekiq'
gem 'airbrake'
gem 'puma'
gem 'sidekiq-cron', '~> 0.3', require: false
gem 'sidekiq-unique-jobs', '~> 4.0'
Gemfile
require 'rubygems'
require 'bundler/setup'
require 'sequel'
require 'dotenv'
require 'rake'
env = ENV['RACK_ENV'] || 'development'
namespace :db do
desc 'Run migrations'
task :migrate, [:version] do |_t, args|
::Dotenv.load(".env", ".env.#{env}")
::Sequel.extension :migration
db = ::Sequel.connect(::ENV.fetch('DATABASE_URL'))
if args[:version]
puts "Migrating to version #{args[:version]}"
::Sequel::Migrator.run(db, 'db/migrations', target: args[:version].to_i)
else
puts 'Migrating to latest'
::Sequel::Migrator.run(db, 'db/migrations')
end
end
end
Rakefile
::Sequel.migration do
transaction
up do
create_table :companies do
primary_key :id
String :company_id, null: false, index: true
String :name, null: false
String :einvoice_address, null: false
String :einvoice_operator, null: false
end
end
down do
drop_table :companies
end
end
db/migrations/001_create_companies.rb
class CompanyUpdaterWorker
include ::Sidekiq::Worker
sidekiq_options unique: :while_executing
URL = "http://verkkolasku.tieke.fi/ExporVLOsoiteToExcel.aspx?type=csv"
def perform
path = ::Tempfile.new('vlo').path
if http_download_uri(::URI.parse(URL), path)
::NetvisorSpreadsheets::CompaniesFillerService.new(path).import
end
end
def http_download_uri(uri, filename)
begin
::Net::HTTP.new(uri.host, uri.port).start do |http|
http.request(Net::HTTP::Get.new(uri.request_uri)) do |response|
::File.open(filename, 'wb') do |io|
response.read_body { |chunk| io.write(chunk) }
end
end
end
rescue Exception => e
return false
end
true
end
end
companies_updater_worker.rb
companies_filler_service.rb
class CompanyUpdaterWorker
include ::Sidekiq::Worker
sidekiq_options unique: :while_executing
URL = "http://verkkolasku.tieke.fi/ExporVLOsoiteToExcel.aspx?type=csv"
def perform
path = ::Tempfile.new('vlo').path
if http_download_uri(::URI.parse(URL), path)
::NetvisorSpreadsheets::CompaniesFillerService.new(path).import
end
end
def http_download_uri(uri, filename)
begin
::Net::HTTP.new(uri.host, uri.port).start do |http|
http.request(Net::HTTP::Get.new(uri.request_uri)) do |response|
::File.open(filename, 'wb') do |io|
response.read_body { |chunk| io.write(chunk) }
end
end
end
rescue Exception => e
return false
end
true
end
end
require 'sinatra/base'
require 'sinatra/json'
module NetvisorSpreadsheets
class Server < Sinatra::Base
configure :production, :development do
enable :logging
set :json_encoder, :to_json
end
get '/' do
if params['company_id'] && params['company_id'].length > 0
json ::NetvisorSpreadsheets::CompanyFinderService.find(params['company_id'])
else
400
end
end
end
end
server.rb
What we get?
• Only 40Mb RAM
• 1 second app load
• Fast deployment
Questions

Weitere ähnliche Inhalte

Was ist angesagt?

Rails engines in large apps
Rails engines in large appsRails engines in large apps
Rails engines in large apps
Enrico Teotti
 
JBoss, Rails and the cloud
JBoss, Rails and the cloudJBoss, Rails and the cloud
JBoss, Rails and the cloud
elliando dias
 
Laravel Restful API and AngularJS
Laravel Restful API and AngularJSLaravel Restful API and AngularJS
Laravel Restful API and AngularJS
Blake Newman
 

Was ist angesagt? (20)

Plug it on!... with railties
Plug it on!... with railtiesPlug it on!... with railties
Plug it on!... with railties
 
Brief Introduction to Ember
Brief Introduction to EmberBrief Introduction to Ember
Brief Introduction to Ember
 
Be Happy With Ruby on Rails - Ecosystem
Be Happy With Ruby on Rails - EcosystemBe Happy With Ruby on Rails - Ecosystem
Be Happy With Ruby on Rails - Ecosystem
 
Intro to Ruby on Rails
Intro to Ruby on RailsIntro to Ruby on Rails
Intro to Ruby on Rails
 
Building web framework with Rack
Building web framework with RackBuilding web framework with Rack
Building web framework with Rack
 
AngularJS meets Rails
AngularJS meets RailsAngularJS meets Rails
AngularJS meets Rails
 
How angularjs saves rails
How angularjs saves railsHow angularjs saves rails
How angularjs saves rails
 
Rails Engines
Rails EnginesRails Engines
Rails Engines
 
Rails engines in large apps
Rails engines in large appsRails engines in large apps
Rails engines in large apps
 
Rails Engine Patterns
Rails Engine PatternsRails Engine Patterns
Rails Engine Patterns
 
PLAT-7 Spring Web Scripts and Spring Surf
PLAT-7 Spring Web Scripts and Spring SurfPLAT-7 Spring Web Scripts and Spring Surf
PLAT-7 Spring Web Scripts and Spring Surf
 
Ninad cucumber rails
Ninad cucumber railsNinad cucumber rails
Ninad cucumber rails
 
Rails Engines as a way to Micro services
Rails Engines as a way to Micro servicesRails Engines as a way to Micro services
Rails Engines as a way to Micro services
 
JBoss, Rails and the cloud
JBoss, Rails and the cloudJBoss, Rails and the cloud
JBoss, Rails and the cloud
 
Namespace less engine
Namespace less engineNamespace less engine
Namespace less engine
 
RoR 101: Session 5
RoR 101: Session 5RoR 101: Session 5
RoR 101: Session 5
 
Laravel Restful API and AngularJS
Laravel Restful API and AngularJSLaravel Restful API and AngularJS
Laravel Restful API and AngularJS
 
Project Fedena and Why Ruby on Rails - ArvindArvind G S
Project Fedena and Why Ruby on Rails - ArvindArvind G SProject Fedena and Why Ruby on Rails - ArvindArvind G S
Project Fedena and Why Ruby on Rails - ArvindArvind G S
 
RoR 101: Session 3
RoR 101: Session 3RoR 101: Session 3
RoR 101: Session 3
 
SPA using Rails & Backbone
SPA using Rails & BackboneSPA using Rails & Backbone
SPA using Rails & Backbone
 

Andere mochten auch

"Walk in a distributed systems park with Orleans" Евгений Бобров
"Walk in a distributed systems park with Orleans" Евгений Бобров"Walk in a distributed systems park with Orleans" Евгений Бобров
"Walk in a distributed systems park with Orleans" Евгений Бобров
Fwdays
 
"От разработчика в консультанты - история одного тренера" Александр Баглай
"От разработчика в консультанты - история одного тренера" Александр Баглай"От разработчика в консультанты - история одного тренера" Александр Баглай
"От разработчика в консультанты - история одного тренера" Александр Баглай
Fwdays
 
"Эффективность и оптимизация кода в Java 8" Сергей Моренец
"Эффективность и оптимизация кода в Java 8" Сергей Моренец"Эффективность и оптимизация кода в Java 8" Сергей Моренец
"Эффективность и оптимизация кода в Java 8" Сергей Моренец
Fwdays
 

Andere mochten auch (20)

"Fun with JavaScript and sensors" by Jan Jongboom
"Fun with JavaScript and sensors" by Jan Jongboom"Fun with JavaScript and sensors" by Jan Jongboom
"Fun with JavaScript and sensors" by Jan Jongboom
 
"Хероковая жизнь" Юрий Литвиненко
"Хероковая жизнь" Юрий Литвиненко"Хероковая жизнь" Юрий Литвиненко
"Хероковая жизнь" Юрий Литвиненко
 
Анна Лаврова "When Fairy Tale meets Reality: Точность-надежность-дизайн"
Анна Лаврова "When Fairy Tale meets Reality: Точность-надежность-дизайн"Анна Лаврова "When Fairy Tale meets Reality: Точность-надежность-дизайн"
Анна Лаврова "When Fairy Tale meets Reality: Точность-надежность-дизайн"
 
Павел Тайкало: "Apple watch first steps"
Павел Тайкало: "Apple watch first steps"Павел Тайкало: "Apple watch first steps"
Павел Тайкало: "Apple watch first steps"
 
Алексей Демедецкий | Unit testing in swift
Алексей Демедецкий | Unit testing in swiftАлексей Демедецкий | Unit testing in swift
Алексей Демедецкий | Unit testing in swift
 
Андрей Уманский и Дмитрий Горин "Нет скучным ретроспективам! Создаём эффектив...
Андрей Уманский и Дмитрий Горин "Нет скучным ретроспективам! Создаём эффектив...Андрей Уманский и Дмитрий Горин "Нет скучным ретроспективам! Создаём эффектив...
Андрей Уманский и Дмитрий Горин "Нет скучным ретроспективам! Создаём эффектив...
 
Максим Климишин "Борьба с асинхронностью в JS"
Максим Климишин "Борьба с асинхронностью в JS"Максим Климишин "Борьба с асинхронностью в JS"
Максим Климишин "Борьба с асинхронностью в JS"
 
"Посмотрим на Акку-Джаву" Дмитрий Мантула
"Посмотрим на Акку-Джаву" Дмитрий Мантула"Посмотрим на Акку-Джаву" Дмитрий Мантула
"Посмотрим на Акку-Джаву" Дмитрий Мантула
 
Александр Корниенко "Как реально построить Dream-team?"
Александр Корниенко "Как реально построить Dream-team?"Александр Корниенко "Как реально построить Dream-team?"
Александр Корниенко "Как реально построить Dream-team?"
 
"Walk in a distributed systems park with Orleans" Евгений Бобров
"Walk in a distributed systems park with Orleans" Евгений Бобров"Walk in a distributed systems park with Orleans" Евгений Бобров
"Walk in a distributed systems park with Orleans" Евгений Бобров
 
"The Grail: React based Isomorph apps framework" Эльдар Джафаров
"The Grail: React based Isomorph apps framework" Эльдар Джафаров"The Grail: React based Isomorph apps framework" Эльдар Джафаров
"The Grail: React based Isomorph apps framework" Эльдар Джафаров
 
"Backbone React Flux" Артем Тритяк
"Backbone React Flux" Артем Тритяк"Backbone React Flux" Артем Тритяк
"Backbone React Flux" Артем Тритяк
 
"От разработчика в консультанты - история одного тренера" Александр Баглай
"От разработчика в консультанты - история одного тренера" Александр Баглай"От разработчика в консультанты - история одного тренера" Александр Баглай
"От разработчика в консультанты - история одного тренера" Александр Баглай
 
"Эффективность и оптимизация кода в Java 8" Сергей Моренец
"Эффективность и оптимизация кода в Java 8" Сергей Моренец"Эффективность и оптимизация кода в Java 8" Сергей Моренец
"Эффективность и оптимизация кода в Java 8" Сергей Моренец
 
Михаил Чалый "Serverless Architectures using .NET and Azure"
Михаил Чалый "Serverless Architectures using .NET and Azure"Михаил Чалый "Serverless Architectures using .NET and Azure"
Михаил Чалый "Serverless Architectures using .NET and Azure"
 
"From CRUD to Hypermedia APIs with Spring" Владимир Цукур
"From CRUD to Hypermedia APIs with Spring" Владимир Цукур"From CRUD to Hypermedia APIs with Spring" Владимир Цукур
"From CRUD to Hypermedia APIs with Spring" Владимир Цукур
 
Сергей Больщиков "Angular Components: все уже за, а вы еще нет?"
Сергей Больщиков "Angular Components: все уже за, а вы еще нет?"Сергей Больщиков "Angular Components: все уже за, а вы еще нет?"
Сергей Больщиков "Angular Components: все уже за, а вы еще нет?"
 
Маргарита Остапчук "Що нового в Windows 10 для розробників"
Маргарита Остапчук "Що нового в Windows 10 для розробників"Маргарита Остапчук "Що нового в Windows 10 для розробників"
Маргарита Остапчук "Що нового в Windows 10 для розробників"
 
"Выучить язык программирования за 25 минут" Дмитрий Мантула
"Выучить язык программирования за 25 минут" Дмитрий Мантула"Выучить язык программирования за 25 минут" Дмитрий Мантула
"Выучить язык программирования за 25 минут" Дмитрий Мантула
 
"Война типов: сильные против слабых" Виктор Полищук
"Война типов: сильные против слабых" Виктор Полищук"Война типов: сильные против слабых" Виктор Полищук
"Война типов: сильные против слабых" Виктор Полищук
 

Ähnlich wie Ruby w/o Rails (Олександр Сімонов)

ChefConf 2012 Spiceweasel
ChefConf 2012 SpiceweaselChefConf 2012 Spiceweasel
ChefConf 2012 Spiceweasel
Matt Ray
 
Learning to code for startup mvp session 3
Learning to code for startup mvp session 3Learning to code for startup mvp session 3
Learning to code for startup mvp session 3
Henry S
 

Ähnlich wie Ruby w/o Rails (Олександр Сімонов) (20)

Strangers In The Night: Ruby, Rack y Sinatra - Herramientas potentes para con...
Strangers In The Night: Ruby, Rack y Sinatra - Herramientas potentes para con...Strangers In The Night: Ruby, Rack y Sinatra - Herramientas potentes para con...
Strangers In The Night: Ruby, Rack y Sinatra - Herramientas potentes para con...
 
Rack
RackRack
Rack
 
Wider than rails
Wider than railsWider than rails
Wider than rails
 
Padrino - the Godfather of Sinatra
Padrino - the Godfather of SinatraPadrino - the Godfather of Sinatra
Padrino - the Godfather of Sinatra
 
Introduction to Rails - presented by Arman Ortega
Introduction to Rails - presented by Arman OrtegaIntroduction to Rails - presented by Arman Ortega
Introduction to Rails - presented by Arman Ortega
 
Rails and the Apache SOLR Search Engine
Rails and the Apache SOLR Search EngineRails and the Apache SOLR Search Engine
Rails and the Apache SOLR Search Engine
 
.NET Architects Day - DNAD 2011
.NET Architects Day - DNAD 2011.NET Architects Day - DNAD 2011
.NET Architects Day - DNAD 2011
 
09 - Fábio Akita - Além do rails
09 - Fábio Akita - Além do rails09 - Fábio Akita - Além do rails
09 - Fábio Akita - Além do rails
 
Ruby on Rails + AngularJS + Twitter Bootstrap
Ruby on Rails + AngularJS + Twitter BootstrapRuby on Rails + AngularJS + Twitter Bootstrap
Ruby on Rails + AngularJS + Twitter Bootstrap
 
ChefConf 2012 Spiceweasel
ChefConf 2012 SpiceweaselChefConf 2012 Spiceweasel
ChefConf 2012 Spiceweasel
 
Introducing the Seneca MVP framework for Node.js
Introducing the Seneca MVP framework for Node.jsIntroducing the Seneca MVP framework for Node.js
Introducing the Seneca MVP framework for Node.js
 
20120816 nodejsdublin
20120816 nodejsdublin20120816 nodejsdublin
20120816 nodejsdublin
 
Sinatra
SinatraSinatra
Sinatra
 
Ruby off Rails (english)
Ruby off Rails (english)Ruby off Rails (english)
Ruby off Rails (english)
 
JRuby, Ruby, Rails and You on the Cloud
JRuby, Ruby, Rails and You on the CloudJRuby, Ruby, Rails and You on the Cloud
JRuby, Ruby, Rails and You on the Cloud
 
Ambiguous Sinatra - Vadim Evseev
Ambiguous Sinatra - Vadim EvseevAmbiguous Sinatra - Vadim Evseev
Ambiguous Sinatra - Vadim Evseev
 
Ambiguous Sinatra
Ambiguous SinatraAmbiguous Sinatra
Ambiguous Sinatra
 
Learning to code for startup mvp session 3
Learning to code for startup mvp session 3Learning to code for startup mvp session 3
Learning to code for startup mvp session 3
 
RSpec on Rails Tutorial
RSpec on Rails TutorialRSpec on Rails Tutorial
RSpec on Rails Tutorial
 
Ecossistema Ruby - versão SCTI UNF 2013
Ecossistema Ruby - versão SCTI UNF 2013Ecossistema Ruby - versão SCTI UNF 2013
Ecossistema Ruby - versão SCTI UNF 2013
 

Mehr von Fwdays

Mehr von Fwdays (20)

"How Preply reduced ML model development time from 1 month to 1 day",Yevhen Y...
"How Preply reduced ML model development time from 1 month to 1 day",Yevhen Y..."How Preply reduced ML model development time from 1 month to 1 day",Yevhen Y...
"How Preply reduced ML model development time from 1 month to 1 day",Yevhen Y...
 
"GenAI Apps: Our Journey from Ideas to Production Excellence",Danil Topchii
"GenAI Apps: Our Journey from Ideas to Production Excellence",Danil Topchii"GenAI Apps: Our Journey from Ideas to Production Excellence",Danil Topchii
"GenAI Apps: Our Journey from Ideas to Production Excellence",Danil Topchii
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
"What is a RAG system and how to build it",Dmytro Spodarets
"What is a RAG system and how to build it",Dmytro Spodarets"What is a RAG system and how to build it",Dmytro Spodarets
"What is a RAG system and how to build it",Dmytro Spodarets
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
"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
 
"Distributed graphs and microservices in Prom.ua", Maksym Kindritskyi
"Distributed graphs and microservices in Prom.ua",  Maksym Kindritskyi"Distributed graphs and microservices in Prom.ua",  Maksym Kindritskyi
"Distributed graphs and microservices in Prom.ua", Maksym Kindritskyi
 
"Rethinking the existing data loading and processing process as an ETL exampl...
"Rethinking the existing data loading and processing process as an ETL exampl..."Rethinking the existing data loading and processing process as an ETL exampl...
"Rethinking the existing data loading and processing process as an ETL exampl...
 
"How Ukrainian IT specialist can go on vacation abroad without crossing the T...
"How Ukrainian IT specialist can go on vacation abroad without crossing the T..."How Ukrainian IT specialist can go on vacation abroad without crossing the T...
"How Ukrainian IT specialist can go on vacation abroad without crossing the T...
 
"The Strength of Being Vulnerable: the experience from CIA, Tesla and Uber", ...
"The Strength of Being Vulnerable: the experience from CIA, Tesla and Uber", ..."The Strength of Being Vulnerable: the experience from CIA, Tesla and Uber", ...
"The Strength of Being Vulnerable: the experience from CIA, Tesla and Uber", ...
 
"[QUICK TALK] Radical candor: how to achieve results faster thanks to a cultu...
"[QUICK TALK] Radical candor: how to achieve results faster thanks to a cultu..."[QUICK TALK] Radical candor: how to achieve results faster thanks to a cultu...
"[QUICK TALK] Radical candor: how to achieve results faster thanks to a cultu...
 
"[QUICK TALK] PDP Plan, the only one door to raise your salary and boost care...
"[QUICK TALK] PDP Plan, the only one door to raise your salary and boost care..."[QUICK TALK] PDP Plan, the only one door to raise your salary and boost care...
"[QUICK TALK] PDP Plan, the only one door to raise your salary and boost care...
 
"4 horsemen of the apocalypse of working relationships (+ antidotes to them)"...
"4 horsemen of the apocalypse of working relationships (+ antidotes to them)"..."4 horsemen of the apocalypse of working relationships (+ antidotes to them)"...
"4 horsemen of the apocalypse of working relationships (+ antidotes to them)"...
 
"Reconnecting with Purpose: Rediscovering Job Interest after Burnout", Anast...
"Reconnecting with Purpose: Rediscovering Job Interest after Burnout",  Anast..."Reconnecting with Purpose: Rediscovering Job Interest after Burnout",  Anast...
"Reconnecting with Purpose: Rediscovering Job Interest after Burnout", Anast...
 
"Mentoring 101: How to effectively invest experience in the success of others...
"Mentoring 101: How to effectively invest experience in the success of others..."Mentoring 101: How to effectively invest experience in the success of others...
"Mentoring 101: How to effectively invest experience in the success of others...
 
"Mission (im) possible: How to get an offer in 2024?", Oleksandra Myronova
"Mission (im) possible: How to get an offer in 2024?",  Oleksandra Myronova"Mission (im) possible: How to get an offer in 2024?",  Oleksandra Myronova
"Mission (im) possible: How to get an offer in 2024?", Oleksandra Myronova
 
"Why have we learned how to package products, but not how to 'package ourselv...
"Why have we learned how to package products, but not how to 'package ourselv..."Why have we learned how to package products, but not how to 'package ourselv...
"Why have we learned how to package products, but not how to 'package ourselv...
 
"How to tame the dragon, or leadership with imposter syndrome", Oleksandr Zin...
"How to tame the dragon, or leadership with imposter syndrome", Oleksandr Zin..."How to tame the dragon, or leadership with imposter syndrome", Oleksandr Zin...
"How to tame the dragon, or leadership with imposter syndrome", Oleksandr Zin...
 

Kürzlich hochgeladen

notes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.pptnotes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.ppt
MsecMca
 
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoorTop Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
dharasingh5698
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
ankushspencer015
 
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Kandungan 087776558899
 
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
dharasingh5698
 

Kürzlich hochgeladen (20)

notes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.pptnotes on Evolution Of Analytic Scalability.ppt
notes on Evolution Of Analytic Scalability.ppt
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.ppt
 
Block diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.pptBlock diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.ppt
 
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
 
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoorTop Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
 
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
 
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
 
Intro To Electric Vehicles PDF Notes.pdf
Intro To Electric Vehicles PDF Notes.pdfIntro To Electric Vehicles PDF Notes.pdf
Intro To Electric Vehicles PDF Notes.pdf
 
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
 
Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdf
 
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - V
 
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
 
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
 

Ruby w/o Rails (Олександр Сімонов)

  • 2. About me • Name: Oleksandr Simonov • Occupation: Founder and Owner of Amoniac • Hobby: Open Source contribution • Github: @simonoff
  • 3. Why Ruby w/o Rails? • Rails is a monolithic stone • Rails is slow • Rails force you to be a lazy
  • 4.
  • 5. rails is: • activerecord • activemodel • activesupport • actionmailer • actionpack • actionview • activejob • railties
  • 8. Alternatives • Rack • Sinatra • Cuba • Grape (API) • Reel • Nahami • Sequel • ROM WEB ORM
  • 9. Advantages • Faster then Rails • Less time for app loading • New knowledge
  • 10. Disadvantages • No Rails like console • No Rails like code autoloading • No Rails helpers • No "Magic" • More code
  • 11. Practical section • Download list of Finnish companies • Insert/Update local DB • On API call returns e-invoice address
  • 12.
  • 13. - app - models - services - workers - config - boot.rb - initializers - 01-dotenv.rb - 02-airbrake.rb - 03-sequel.rb - 04-sidekiq.rb - db - migrations - init.rb - config.ru Structure
  • 14. require 'rubygems' require 'bundler/setup' require_relative 'init' # Application code loading require 'sidekiq/web' use Rack::ContentLength use Rack::CommonLogger, ::NetvisorSpreadsheets. logger # use own logger use Rack::ShowExceptions run Rack::URLMap.new('/' => ::NetvisorSpreadsheets: :Server, '/sidekiq' => Sidekiq::Web) config.ru
  • 15. init.rb # encoding: UTF-8 ENV['RACK_ENV'] ||= 'development' # default environment require 'rubygems' module NetvisorSpreadsheets # Singletone extend self attr_accessor :db def root # helper for get application root path @root_path ||= ::Pathname.new(::File.join(File.dirname(__FILE__))).expand_path end def env # helper for get environment @env ||= ENV["RACK_ENV"] || "development" end def logger # helper for logger @logger ||= ::Logger.new(self.root.join('log', "#{self.env}.log").to_s) end end ::NetvisorSpreadsheets.logger.level = if ::NetvisorSpreadsheets.env == 'production' ::Logger::INFO else ::Logger::DEBUG end # require boot file require self.root.join('config', 'boot.rb').to_s
  • 16. $LOAD_PATH.unshift ::NetvisorSpreadsheets.root # add root path to load path # autoload some initializers, models, workers and services def load_folder(*path) ::Dir.glob(::NetvisorSpreadsheets.root.join(*path)).each { |r| require r } end load_folder('config', 'initializers', '**/*.rb') load_folder('app', 'models', '**/*.rb') load_folder('app', 'workers', '**/*.rb') load_folder('app', 'services', '**/*.rb') # require sinatra server code require 'config/server' boot.rb
  • 17. source 'https://rubygems.org' gem 'sqlite3' gem 'dotenv' gem 'sequel' gem 'sinatra' gem 'sinatra-contrib' gem 'sidekiq' gem 'airbrake' gem 'puma' gem 'sidekiq-cron', '~> 0.3', require: false gem 'sidekiq-unique-jobs', '~> 4.0' Gemfile
  • 18. require 'rubygems' require 'bundler/setup' require 'sequel' require 'dotenv' require 'rake' env = ENV['RACK_ENV'] || 'development' namespace :db do desc 'Run migrations' task :migrate, [:version] do |_t, args| ::Dotenv.load(".env", ".env.#{env}") ::Sequel.extension :migration db = ::Sequel.connect(::ENV.fetch('DATABASE_URL')) if args[:version] puts "Migrating to version #{args[:version]}" ::Sequel::Migrator.run(db, 'db/migrations', target: args[:version].to_i) else puts 'Migrating to latest' ::Sequel::Migrator.run(db, 'db/migrations') end end end Rakefile
  • 19. ::Sequel.migration do transaction up do create_table :companies do primary_key :id String :company_id, null: false, index: true String :name, null: false String :einvoice_address, null: false String :einvoice_operator, null: false end end down do drop_table :companies end end db/migrations/001_create_companies.rb
  • 20. class CompanyUpdaterWorker include ::Sidekiq::Worker sidekiq_options unique: :while_executing URL = "http://verkkolasku.tieke.fi/ExporVLOsoiteToExcel.aspx?type=csv" def perform path = ::Tempfile.new('vlo').path if http_download_uri(::URI.parse(URL), path) ::NetvisorSpreadsheets::CompaniesFillerService.new(path).import end end def http_download_uri(uri, filename) begin ::Net::HTTP.new(uri.host, uri.port).start do |http| http.request(Net::HTTP::Get.new(uri.request_uri)) do |response| ::File.open(filename, 'wb') do |io| response.read_body { |chunk| io.write(chunk) } end end end rescue Exception => e return false end true end end companies_updater_worker.rb
  • 21. companies_filler_service.rb class CompanyUpdaterWorker include ::Sidekiq::Worker sidekiq_options unique: :while_executing URL = "http://verkkolasku.tieke.fi/ExporVLOsoiteToExcel.aspx?type=csv" def perform path = ::Tempfile.new('vlo').path if http_download_uri(::URI.parse(URL), path) ::NetvisorSpreadsheets::CompaniesFillerService.new(path).import end end def http_download_uri(uri, filename) begin ::Net::HTTP.new(uri.host, uri.port).start do |http| http.request(Net::HTTP::Get.new(uri.request_uri)) do |response| ::File.open(filename, 'wb') do |io| response.read_body { |chunk| io.write(chunk) } end end end rescue Exception => e return false end true end end
  • 22. require 'sinatra/base' require 'sinatra/json' module NetvisorSpreadsheets class Server < Sinatra::Base configure :production, :development do enable :logging set :json_encoder, :to_json end get '/' do if params['company_id'] && params['company_id'].length > 0 json ::NetvisorSpreadsheets::CompanyFinderService.find(params['company_id']) else 400 end end end end server.rb
  • 23.
  • 24. What we get? • Only 40Mb RAM • 1 second app load • Fast deployment