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
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
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
We should set the expectations that you should have from this talk. And also what I expect from the audience.
What is DSL anyway!!
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.
Ruby is pretty close to a plain english language with a touch of programmer’s syntax.
You might have see these DSLs, or even used them a lot if you have worked with Rails.
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.