Write ruby code to
change ruby code
Richard Huang
Xinmin Labs
Slide 2
Slide 2 text
About Me
Founder at Xinmin Labs
Full Stack Developer
Open Source Enthusiast
@flyerhzm
Slide 3
Slide 3 text
Problem
Slide 4
Slide 4 text
Hey, let’s use rspec new syntax for project A
Yes, sure, I love the rspec new syntax
Slide 5
Slide 5 text
Hey, let’s use rspec new syntax for project B
Hmmm…ok
Slide 6
Slide 6 text
Hey, let’s use rspec new syntax for project C
Oh, no, I don’t want to repeat it again
Slide 7
Slide 7 text
Developers love upgrading
and refactoring code
Slide 8
Slide 8 text
Developers hate changing
code again and again
Slide 9
Slide 9 text
Automation
Slide 10
Slide 10 text
Metric Tools
Slide 11
Slide 11 text
Metric Tools
• cane - fails your build if code quality thresholds
are not met
• reek - is a tool that examines Ruby classes,
modules and methods and reports any code
smells it finds.
• rails_best_practices - is a tool to check the quality
of rails code.
• ……
Slide 12
Slide 12 text
Tell you what to do,
but can’t do for you
Slide 13
Slide 13 text
IDE
Slide 14
Slide 14 text
IDE
• can rename class / method / variable name
• can extract methods
• can ……
Slide 15
Slide 15 text
IDE
• can’t customize
Slide 16
Slide 16 text
Based on text
Slide 17
Slide 17 text
Based on text
Replace FactoryGirl.create with create
!
$ sed -i '' 's/FactoryGirl.create/create/g' spec/**/*.rb
Slide 18
Slide 18 text
Based on text
Replace FactoryGirl.create with create
!
!
Slide 19
Slide 19 text
Based on text
Hard to be accurate
!
!
!
!
Slide 20
Slide 20 text
Based on text
Hard to convert complicated cases
!
!
!
!
Slide 21
Slide 21 text
Based on AST
Slide 22
Slide 22 text
What’s AST
AST is short for Abstract Syntax Tree
Slide 23
Slide 23 text
What’s AST
Slide 24
Slide 24 text
Why AST
It is much more accurate to parse ruby code.
Slide 25
Slide 25 text
No content
Slide 26
Slide 26 text
No content
Slide 27
Slide 27 text
How to use AST
• ripper
• ParseTree - https://github.com/seattlerb/parsetree
• ruby_parser - https://github.com/seattlerb/ruby_parser
• parser - https://github.com/whitequark/parser
Slide 28
Slide 28 text
How to use AST
Slide 29
Slide 29 text
Example
transpec - https://github.com/yujinakayama/
transpec
Slide 30
Slide 30 text
No content
Slide 31
Slide 31 text
Based on AST
Accurate, but hard to write and read
Slide 32
Slide 32 text
Synvert
https://github.com/xinminlabs/synvert
Slide 33
Slide 33 text
Demo
http://xinminlabs.github.io/synvert/
Slide 34
Slide 34 text
No content
Slide 35
Slide 35 text
Synvert
• Add useful attributes to AST nodes
!
• Provide DSL to parse and rewrite code
Slide 36
Slide 36 text
Attributes for AST node
Slide 37
Slide 37 text
Attributes for AST node
Slide 38
Slide 38 text
Attributes for AST node
Slide 39
Slide 39 text
Attributes for AST node
Check out more attributes
http://xinminlabs.github.io/synvert/rules/