SlideShare a Scribd company logo
1 of 24
Ruby DSL
Crafting beautiful code
You know basic Ruby
OR get you interested to know Ruby
Feel free to ask questions
Will only scratch the surface
After this, you can write a basic Ruby DSL
Expectations
DSL !!!
describe '#destroy'
context 'when resource is found'
it 'has 200 status code if logged in'
expect response to respond with 200
end
end
end
DSL ???
Test
X
DSL you might have seen in Ruby
describe '#destroy' do
context 'when resource is found' do
it 'has 200 status code if logged in' do
expect(response).to respond_with 200
end
end
end
RSpec
DSL you might have seen in Ruby
create_table :users do |t|
t.string :name
t.attachment :avatar
t.timestamps
end
DB Migrations
DSL you might have seen in Ruby
Rails.application.routes.draw do
root 'pages#home'
resources :pages, only: [:index, :show]
end
Rails Routing
What is DSL??
API that is tailored to
express Domain Logic
Language
VS
DSL
Why DSL ???
Simple to express
Embraces domain in code
Powerful abstraction that allows you to
change
Let’s start
Keys to Ruby DSL
Code blocks
instance_eval
Code blocks
Ruby code block
def report
puts "Header"
yield
puts "Footer"
end
report do
puts "From block"
end
Code Output
Header
From block
Footer
REPL
instance_eval
class Report
def initialize(&block)
puts "Header"
instance_eval &block
puts "Footer"
end
end
Report.new do
puts "From block"
end
Ruby instance_eval
class Report
def initialize(&block)
puts "Header"
instance_eval &block
puts "Footer"
end
def my_print(str)
puts str
end
end
Ruby instance_eval - 02
Report.new do
my_print "From block"
end
REPL
class Report
def initialize(data, &block)
@data = data; @columns = []
instance_eval &block
end
def column(column_name) @columns << column_name end
def print
@data.each { |row| @columns.each { |column| puts row[column] } }
end
end
Ruby instance_eval - 03
data = [
{name: 'Jitu', age: 34},
{name: 'Razeen', age: 3}
]
report = Report.new(data) do
column :name
end
report.print()
Ruby instance_eval - 03
Jitu
Razeen
REPL
My experience
In one of the rails project I worked on had a tons of reports, which needed the
following features
Queries, which are easy to understand and change
Filters
Pagination
Generate PDF, CSV, and email those reports
Generate graph in HTML and in PDF
DSL for generating reports
def index
reporter(Invoice.scoped) do
filter :title, type: :text
filter :created_at, type: :date
column :title { |invoice| link_to invoice.title, invoice }
column :total_paid, show_total: true
column :total_charged, show_total: true
column :paid
end
end
Demo
Author
A.K.M. Ashrafuzzaman
Software Engineer,
Newscred.
http://ashrafuzzaman.github.io
References
Link to this slide
Blogs
DSL QandA by Martin Fowler
Creating a Ruby DSL, by Leigh Halliday
Source code
Source codes for this slide
query_report gem

More Related Content

What's hot

JavaScript: Patterns, Part 2
JavaScript: Patterns, Part  2JavaScript: Patterns, Part  2
JavaScript: Patterns, Part 2
Chris Farrell
 
Functional programming in scala
Functional programming in scalaFunctional programming in scala
Functional programming in scala
Stratio
 

What's hot (20)

Intro to Asynchronous Javascript
Intro to Asynchronous JavascriptIntro to Asynchronous Javascript
Intro to Asynchronous Javascript
 
PHP: GraphQL consistency through code generation
PHP: GraphQL consistency through code generationPHP: GraphQL consistency through code generation
PHP: GraphQL consistency through code generation
 
Angular Weekend
Angular WeekendAngular Weekend
Angular Weekend
 
Javascript
JavascriptJavascript
Javascript
 
Use the @types, Luke
Use the @types, LukeUse the @types, Luke
Use the @types, Luke
 
Introduction to Elm
Introduction to ElmIntroduction to Elm
Introduction to Elm
 
Lombok
LombokLombok
Lombok
 
Scala : language of the future
Scala : language of the futureScala : language of the future
Scala : language of the future
 
JavaScript: Patterns, Part 2
JavaScript: Patterns, Part  2JavaScript: Patterns, Part  2
JavaScript: Patterns, Part 2
 
A (very brief) into to Functional Programming
A (very brief) into to Functional ProgrammingA (very brief) into to Functional Programming
A (very brief) into to Functional Programming
 
Project Lombok!
Project Lombok!Project Lombok!
Project Lombok!
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
 
Scala: functional programming for the imperative mind
Scala: functional programming for the imperative mindScala: functional programming for the imperative mind
Scala: functional programming for the imperative mind
 
JavaScript Functions
JavaScript FunctionsJavaScript Functions
JavaScript Functions
 
Python Programming Basics for begginners
Python Programming Basics for begginnersPython Programming Basics for begginners
Python Programming Basics for begginners
 
What's a macro?: Learning by Examples / Scalaのマクロに実用例から触れてみよう!
What's a macro?: Learning by Examples / Scalaのマクロに実用例から触れてみよう!What's a macro?: Learning by Examples / Scalaのマクロに実用例から触れてみよう!
What's a macro?: Learning by Examples / Scalaのマクロに実用例から触れてみよう!
 
Practical TypeScript
Practical TypeScriptPractical TypeScript
Practical TypeScript
 
Java script tutorial
Java script tutorialJava script tutorial
Java script tutorial
 
Arrays &amp; functions in php
Arrays &amp; functions in phpArrays &amp; functions in php
Arrays &amp; functions in php
 
Functional programming in scala
Functional programming in scalaFunctional programming in scala
Functional programming in scala
 

Similar to RubyConf Bangladesh 2017 - Craft beautiful code with Ruby DSL

Building DSLs On CLR and DLR (Microsoft.NET)
Building DSLs On CLR and DLR (Microsoft.NET)Building DSLs On CLR and DLR (Microsoft.NET)
Building DSLs On CLR and DLR (Microsoft.NET)
Vitaly Baum
 
Introduction to Ruby on Rails
Introduction to Ruby on RailsIntroduction to Ruby on Rails
Introduction to Ruby on Rails
Manoj Kumar
 
Ruby -the wheel Technology
Ruby -the wheel TechnologyRuby -the wheel Technology
Ruby -the wheel Technology
ppparthpatel123
 
Fast Web Applications Development with Ruby on Rails on Oracle
Fast Web Applications Development with Ruby on Rails on OracleFast Web Applications Development with Ruby on Rails on Oracle
Fast Web Applications Development with Ruby on Rails on Oracle
Raimonds Simanovskis
 
Smoothing Your Java with DSLs
Smoothing Your Java with DSLsSmoothing Your Java with DSLs
Smoothing Your Java with DSLs
intelliyole
 
Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)
Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)
Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)
lennartkats
 

Similar to RubyConf Bangladesh 2017 - Craft beautiful code with Ruby DSL (20)

Building DSLs On CLR and DLR (Microsoft.NET)
Building DSLs On CLR and DLR (Microsoft.NET)Building DSLs On CLR and DLR (Microsoft.NET)
Building DSLs On CLR and DLR (Microsoft.NET)
 
Wider than rails
Wider than railsWider than rails
Wider than rails
 
Ruby on Rails Presentation
Ruby on Rails PresentationRuby on Rails Presentation
Ruby on Rails Presentation
 
Ruby on Rails introduction
Ruby on Rails introduction Ruby on Rails introduction
Ruby on Rails introduction
 
Introduction to Ruby on Rails
Introduction to Ruby on RailsIntroduction to Ruby on Rails
Introduction to Ruby on Rails
 
Ruby -the wheel Technology
Ruby -the wheel TechnologyRuby -the wheel Technology
Ruby -the wheel Technology
 
Ruby On Rails Introduction
Ruby On Rails IntroductionRuby On Rails Introduction
Ruby On Rails Introduction
 
Fast Web Applications Development with Ruby on Rails on Oracle
Fast Web Applications Development with Ruby on Rails on OracleFast Web Applications Development with Ruby on Rails on Oracle
Fast Web Applications Development with Ruby on Rails on Oracle
 
Rspec
RspecRspec
Rspec
 
Ruby on Rails For .Net Programmers
Ruby on Rails For .Net ProgrammersRuby on Rails For .Net Programmers
Ruby on Rails For .Net Programmers
 
Phoenix for Rails Devs
Phoenix for Rails DevsPhoenix for Rails Devs
Phoenix for Rails Devs
 
Rochester on Rails: Introduction to Rails
Rochester on Rails: Introduction to RailsRochester on Rails: Introduction to Rails
Rochester on Rails: Introduction to Rails
 
"ClojureScript journey: from little script, to CLI program, to AWS Lambda fun...
"ClojureScript journey: from little script, to CLI program, to AWS Lambda fun..."ClojureScript journey: from little script, to CLI program, to AWS Lambda fun...
"ClojureScript journey: from little script, to CLI program, to AWS Lambda fun...
 
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
 
Ruby on Rails workshop for beginner
Ruby on Rails workshop for beginnerRuby on Rails workshop for beginner
Ruby on Rails workshop for beginner
 
Connecting the Worlds of Java and Ruby with JRuby
Connecting the Worlds of Java and Ruby with JRubyConnecting the Worlds of Java and Ruby with JRuby
Connecting the Worlds of Java and Ruby with JRuby
 
Smoothing Your Java with DSLs
Smoothing Your Java with DSLsSmoothing Your Java with DSLs
Smoothing Your Java with DSLs
 
Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)
Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)
Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)
 
Otimizando Aplicações em Rails
Otimizando Aplicações em RailsOtimizando Aplicações em Rails
Otimizando Aplicações em Rails
 
Ruby on Rails
Ruby on RailsRuby on Rails
Ruby on Rails
 

More from Ruby Bangladesh

More from Ruby Bangladesh (7)

RubyConf Bangladesh 2017 - Introduction to Ruby on Rails
RubyConf Bangladesh 2017 - Introduction to Ruby on RailsRubyConf Bangladesh 2017 - Introduction to Ruby on Rails
RubyConf Bangladesh 2017 - Introduction to Ruby on Rails
 
RubyConf Bangladesh 2017 - Core Ruby: How it works
RubyConf Bangladesh 2017 - Core Ruby: How it worksRubyConf Bangladesh 2017 - Core Ruby: How it works
RubyConf Bangladesh 2017 - Core Ruby: How it works
 
RubyConf Bangladesh 2017 - Speed up your API/backend
RubyConf Bangladesh 2017 - Speed up your API/backendRubyConf Bangladesh 2017 - Speed up your API/backend
RubyConf Bangladesh 2017 - Speed up your API/backend
 
RubyConf Bangladesh 2017 - Which language should I choose
RubyConf Bangladesh 2017 - Which language should I chooseRubyConf Bangladesh 2017 - Which language should I choose
RubyConf Bangladesh 2017 - Which language should I choose
 
RubyConf Bangladesh 2017 - Elixir for Rubyists
RubyConf Bangladesh 2017 - Elixir for RubyistsRubyConf Bangladesh 2017 - Elixir for Rubyists
RubyConf Bangladesh 2017 - Elixir for Rubyists
 
RubyConf Bangladesh 2017 - Rails buggy code
RubyConf Bangladesh 2017 - Rails buggy codeRubyConf Bangladesh 2017 - Rails buggy code
RubyConf Bangladesh 2017 - Rails buggy code
 
Rubyconf Bangladesh 2017 - Lets start coding in Ruby
Rubyconf Bangladesh 2017 - Lets start coding in RubyRubyconf Bangladesh 2017 - Lets start coding in Ruby
Rubyconf Bangladesh 2017 - Lets start coding in Ruby
 

Recently uploaded

Team Transformation Tactics for Holistic Testing and Quality (NewCrafts Paris...
Team Transformation Tactics for Holistic Testing and Quality (NewCrafts Paris...Team Transformation Tactics for Holistic Testing and Quality (NewCrafts Paris...
Team Transformation Tactics for Holistic Testing and Quality (NewCrafts Paris...
Lisi Hocke
 

Recently uploaded (20)

Community is Just as Important as Code by Andrea Goulet
Community is Just as Important as Code by Andrea GouletCommunity is Just as Important as Code by Andrea Goulet
Community is Just as Important as Code by Andrea Goulet
 
Software Engineering - Introduction + Process Models + Requirements Engineering
Software Engineering - Introduction + Process Models + Requirements EngineeringSoftware Engineering - Introduction + Process Models + Requirements Engineering
Software Engineering - Introduction + Process Models + Requirements Engineering
 
Anypoint Code Builder - Munich MuleSoft Meetup - 16th May 2024
Anypoint Code Builder - Munich MuleSoft Meetup - 16th May 2024Anypoint Code Builder - Munich MuleSoft Meetup - 16th May 2024
Anypoint Code Builder - Munich MuleSoft Meetup - 16th May 2024
 
Test Automation Design Patterns_ A Comprehensive Guide.pdf
Test Automation Design Patterns_ A Comprehensive Guide.pdfTest Automation Design Patterns_ A Comprehensive Guide.pdf
Test Automation Design Patterns_ A Comprehensive Guide.pdf
 
Abortion Pill Prices Germiston ](+27832195400*)[ 🏥 Women's Abortion Clinic in...
Abortion Pill Prices Germiston ](+27832195400*)[ 🏥 Women's Abortion Clinic in...Abortion Pill Prices Germiston ](+27832195400*)[ 🏥 Women's Abortion Clinic in...
Abortion Pill Prices Germiston ](+27832195400*)[ 🏥 Women's Abortion Clinic in...
 
Abortion Clinic In Johannesburg ](+27832195400*)[ 🏥 Safe Abortion Pills in Jo...
Abortion Clinic In Johannesburg ](+27832195400*)[ 🏥 Safe Abortion Pills in Jo...Abortion Clinic In Johannesburg ](+27832195400*)[ 🏥 Safe Abortion Pills in Jo...
Abortion Clinic In Johannesburg ](+27832195400*)[ 🏥 Safe Abortion Pills in Jo...
 
CERVED e Neo4j su una nuvola, migrazione ed evoluzione di un grafo mission cr...
CERVED e Neo4j su una nuvola, migrazione ed evoluzione di un grafo mission cr...CERVED e Neo4j su una nuvola, migrazione ed evoluzione di un grafo mission cr...
CERVED e Neo4j su una nuvola, migrazione ed evoluzione di un grafo mission cr...
 
Abortion Pill Prices Mthatha (@](+27832195400*)[ 🏥 Women's Abortion Clinic In...
Abortion Pill Prices Mthatha (@](+27832195400*)[ 🏥 Women's Abortion Clinic In...Abortion Pill Prices Mthatha (@](+27832195400*)[ 🏥 Women's Abortion Clinic In...
Abortion Pill Prices Mthatha (@](+27832195400*)[ 🏥 Women's Abortion Clinic In...
 
Effective Strategies for Wix's Scaling challenges - GeeCon
Effective Strategies for Wix's Scaling challenges - GeeConEffective Strategies for Wix's Scaling challenges - GeeCon
Effective Strategies for Wix's Scaling challenges - GeeCon
 
Automate your OpenSIPS config tests - OpenSIPS Summit 2024
Automate your OpenSIPS config tests - OpenSIPS Summit 2024Automate your OpenSIPS config tests - OpenSIPS Summit 2024
Automate your OpenSIPS config tests - OpenSIPS Summit 2024
 
Team Transformation Tactics for Holistic Testing and Quality (NewCrafts Paris...
Team Transformation Tactics for Holistic Testing and Quality (NewCrafts Paris...Team Transformation Tactics for Holistic Testing and Quality (NewCrafts Paris...
Team Transformation Tactics for Holistic Testing and Quality (NewCrafts Paris...
 
Abortion Pill Prices Turfloop ](+27832195400*)[ 🏥 Women's Abortion Clinic in ...
Abortion Pill Prices Turfloop ](+27832195400*)[ 🏥 Women's Abortion Clinic in ...Abortion Pill Prices Turfloop ](+27832195400*)[ 🏥 Women's Abortion Clinic in ...
Abortion Pill Prices Turfloop ](+27832195400*)[ 🏥 Women's Abortion Clinic in ...
 
Weeding your micro service landscape.pdf
Weeding your micro service landscape.pdfWeeding your micro service landscape.pdf
Weeding your micro service landscape.pdf
 
Abortion Pill Prices Jane Furse ](+27832195400*)[ 🏥 Women's Abortion Clinic i...
Abortion Pill Prices Jane Furse ](+27832195400*)[ 🏥 Women's Abortion Clinic i...Abortion Pill Prices Jane Furse ](+27832195400*)[ 🏥 Women's Abortion Clinic i...
Abortion Pill Prices Jane Furse ](+27832195400*)[ 🏥 Women's Abortion Clinic i...
 
Workshop: Enabling GenAI Breakthroughs with Knowledge Graphs - GraphSummit Milan
Workshop: Enabling GenAI Breakthroughs with Knowledge Graphs - GraphSummit MilanWorkshop: Enabling GenAI Breakthroughs with Knowledge Graphs - GraphSummit Milan
Workshop: Enabling GenAI Breakthroughs with Knowledge Graphs - GraphSummit Milan
 
Navigation in flutter – how to add stack, tab, and drawer navigators to your ...
Navigation in flutter – how to add stack, tab, and drawer navigators to your ...Navigation in flutter – how to add stack, tab, and drawer navigators to your ...
Navigation in flutter – how to add stack, tab, and drawer navigators to your ...
 
Your Ultimate Web Studio for Streaming Anywhere | Evmux
Your Ultimate Web Studio for Streaming Anywhere | EvmuxYour Ultimate Web Studio for Streaming Anywhere | Evmux
Your Ultimate Web Studio for Streaming Anywhere | Evmux
 
Abortion Pill Prices Jozini ](+27832195400*)[ 🏥 Women's Abortion Clinic in Jo...
Abortion Pill Prices Jozini ](+27832195400*)[ 🏥 Women's Abortion Clinic in Jo...Abortion Pill Prices Jozini ](+27832195400*)[ 🏥 Women's Abortion Clinic in Jo...
Abortion Pill Prices Jozini ](+27832195400*)[ 🏥 Women's Abortion Clinic in Jo...
 
Auto Affiliate AI Earns First Commission in 3 Hours..pdf
Auto Affiliate  AI Earns First Commission in 3 Hours..pdfAuto Affiliate  AI Earns First Commission in 3 Hours..pdf
Auto Affiliate AI Earns First Commission in 3 Hours..pdf
 
Modern binary build systems - PyCon 2024
Modern binary build systems - PyCon 2024Modern binary build systems - PyCon 2024
Modern binary build systems - PyCon 2024
 

RubyConf Bangladesh 2017 - Craft beautiful code with Ruby DSL

  • 2. You know basic Ruby OR get you interested to know Ruby Feel free to ask questions Will only scratch the surface After this, you can write a basic Ruby DSL Expectations
  • 4. describe '#destroy' context 'when resource is found' it 'has 200 status code if logged in' expect response to respond with 200 end end end DSL ??? Test X
  • 5. DSL you might have seen in Ruby describe '#destroy' do context 'when resource is found' do it 'has 200 status code if logged in' do expect(response).to respond_with 200 end end end RSpec
  • 6. DSL you might have seen in Ruby create_table :users do |t| t.string :name t.attachment :avatar t.timestamps end DB Migrations
  • 7. DSL you might have seen in Ruby Rails.application.routes.draw do root 'pages#home' resources :pages, only: [:index, :show] end Rails Routing
  • 8. What is DSL?? API that is tailored to express Domain Logic
  • 10. Why DSL ??? Simple to express Embraces domain in code Powerful abstraction that allows you to change
  • 12. Keys to Ruby DSL Code blocks instance_eval
  • 14. Ruby code block def report puts "Header" yield puts "Footer" end report do puts "From block" end Code Output Header From block Footer REPL
  • 16. class Report def initialize(&block) puts "Header" instance_eval &block puts "Footer" end end Report.new do puts "From block" end Ruby instance_eval
  • 17. class Report def initialize(&block) puts "Header" instance_eval &block puts "Footer" end def my_print(str) puts str end end Ruby instance_eval - 02 Report.new do my_print "From block" end REPL
  • 18. class Report def initialize(data, &block) @data = data; @columns = [] instance_eval &block end def column(column_name) @columns << column_name end def print @data.each { |row| @columns.each { |column| puts row[column] } } end end Ruby instance_eval - 03
  • 19. data = [ {name: 'Jitu', age: 34}, {name: 'Razeen', age: 3} ] report = Report.new(data) do column :name end report.print() Ruby instance_eval - 03 Jitu Razeen REPL
  • 20. My experience In one of the rails project I worked on had a tons of reports, which needed the following features Queries, which are easy to understand and change Filters Pagination Generate PDF, CSV, and email those reports Generate graph in HTML and in PDF
  • 21. DSL for generating reports def index reporter(Invoice.scoped) do filter :title, type: :text filter :created_at, type: :date column :title { |invoice| link_to invoice.title, invoice } column :total_paid, show_total: true column :total_charged, show_total: true column :paid end end
  • 22. Demo
  • 24. References Link to this slide Blogs DSL QandA by Martin Fowler Creating a Ruby DSL, by Leigh Halliday Source code Source codes for this slide query_report gem

Editor's Notes

  1. We should set the expectations that you should have from this talk. And also what I expect from the audience.
  2. What is DSL anyway!!
  3. It would be great if we could write in plain english to express our business logic. And business domain, that even the business people might understand.
  4. Ruby is pretty close to a plain english language with a touch of programmer’s syntax.
  5. You might have see these DSLs, or even used them a lot if you have worked with Rails.
  6. DSL means Domain Specific Language. It does not mean that it is a different language where you would have to write your own parser and context free grammar. It means that your code embraces the business domain. And it is clearly understood by reading the code how the business works.