SlideShare una empresa de Scribd logo
1 de 60
Hacking with ruby2ruby
         Marc Chung
           OpenRain
      blog.marcchung.com
       blog.openrain.com
        @heisenthought
Hacking with ruby2ruby
         Marc Chung
           OpenRain
      blog.marcchung.com
       blog.openrain.com
        @heisenthought
ruby2ruby

   Ruby2Ruby
Walks the Ruby AST
  To emit Ruby
sudo gem install ruby2ruby
Limitations

• Only Ruby 1.8
• Not 1.9, yet
• Built into Rubinius
function rhino_rocks() {
   return “Rhino, rocks!”;
}
js> rhino_rocks();

Rhino, rocks!
js> rhino_rocks.toString();

function rhino_rocks() {
   return “Rhino, rocks!”;
}
js> eval(rhino_rocks.toString()).call();

Rhino, rocks!
ruby_rocks = proc {
  return “Ruby, rocks”;
}
irb> ruby_rocks.call;

Ruby, rocks!
irb> require “ruby2ruby”
irb> require “parse_tree_extensions”
irb> ruby_rocks.to_ruby

proc { return “Ruby, rocks” }
irb> eval(ruby_rocks.to_ruby).call

Ruby, rocks!
define_method
class Voice
  define_method(:shout) do |word|
    word.upcase!
  end
end

puts Ruby2Ruby.translate(Voice)
class Voice < Object
   def yell(word)
      word.upcase!
   end
end
alias
class AliasClass
   def old_busted
     quot;42quot;
   end

  alias_method :new_hotness, :old_busted
end

puts Ruby2Ruby.translate(AliasClass)
class AliasClass < Object
   def new_hotness
     quot;42quot;
   end

  def old_busted
    quot;42quot;
  end
end
#module_function
module HelperModule
  def help
    puts quot;Help mequot;
  end
  module_function : help
end

puts Ruby2Ruby.translate(HelperModule)
module HelperModule
  def help
   puts(quot;Help mequot;)
  end

  def self. help
    puts(quot;Help mequot;)
  end
end
ActiveRecord Models

 class Doctor < ActiveRecord::Base
    has_many :patients
 end
See, Ruby, Run!

• Drmap
• git clone git://github.com/mchung/drmap.git
• Optionally, install Journeta
Under the hood

• Abstract syntax trees
• S-expressions
• ParseTree
class Book
   def title
      “Ruby programming”
   end
end
case NODE_BREAK:
case NODE_NEXT:
 if (node->nd_stts)
   add_to_parse_tree(self, current, node->nd_stts, locals);

 break;

case NODE_YIELD:
 if (node->nd_stts)
   add_to_parse_tree(self, current, node->nd_stts, locals);

 if (node->nd_stts
     && (nd_type(node->nd_stts) == NODE_ARRAY
       || nd_type(node->nd_stts) == NODE_ZARRAY)
     && !node->nd_state)
   rb_ary_push(current, Qtrue);

 break;
[:class, :Book,
    [:const, :Object],
    [:defn, :title, [:scope, [:block,
       [:args], [:str, quot;Ruby programmingquot;]]]]]
class Book < Object
   def title
    “Ruby programming”
   end
end
/opt/local/usr/bin


• parse_tree_show
• r2r_show
class Book
   def title
      “Ruby programming”
   end
end
$ parse_tree_show book.rb
s(:class, :Book,
   nil,
   s(:scope,
       s(:defn, :title,
       s(:args),
           s(:scope, s(:block,
              s(:str, quot;Ruby programmingquot;))))))
$ r2r_show book.rb
class Book
   def title()
      “Ruby programming”
   end
end
Operator Precedence
with Guy Decoux: a b c, d
            [[:fcall, :a,
                [:array,
                   [:fcall, :b,
                   [:array,
                        [:vcall, :c],
                        [:vcall, :d]]]]]]

ParseTree.new.parse_tree_for_string(“a b c, d”)
ruby2java
class JavaClass
   def self.main
     puts “Java, rocks!”
   end
end
[:class, :JavaClass,
    [:const, :Object],
    [:defs, [:self], :main,
       [:scope,
       [:block, [:args],
           [:fcall, :puts, [:array, [:str, quot;Hello, Javaquot;]]]]]]]
class Ruby2Java < SexpProcessor
   def process_class(exp)
      “public class #{exp.shift} #{next_token(exp, true)}”
   end

  def process_const(exp)
    “extends #{exp.shift}”
  end
....
end
public class JavaClass {
  public static void main(String argv[]) {
      return “Hello, Java”;
  }
}
Distributing Ruby


• drmap - multi-machine worker queue
• gisting - map/reduce framework
drmap
irb> fn = proc {|x| x**10}
irb> YAML::dump(fn)
=> quot;--- !ruby/object:Proc {}nnquot;
irb> Marshal.dump(fn)
TypeError: no marshal_dump is defined for class Proc
irb> YAML::dump(fn.to_ruby)
=> quot;--- proc { |x| (x ** 10) }nquot;
irb> Marshal.dump(fn.to_ruby)
=> quot;004bquot;eproc { |x| (x ** 10) }quot;
Enumerable#drmap
module Enumerable

 def drmap(&block)
  pool = Drmap::BeanstalkPool.new

  jid = rand(100)
  each_with_index do |element, idx|
    pool.put_job(jid, block.to_ruby, element)
  end

  results = []
  while results.size < length
   results << pool.next_result(jid)
  end
  results
 end

end
def process
  loop do
      begin
         job_payload = next_job
         fn = job_payload[:proc]
         data = job_payload[:data]
         result = eval(fn).call(data)
         save(job_payload[:jid], result)
         success!
      rescue => e
         fail!(e)
      end
  end
end
drmap

• Trivial
• Distributed
• Powerful
Demo time!
Gisting


• MapReduce in Ruby
• http://github.com/mchung/gisting
map / reduce

• Functional programming
• Iterating over collections
• (5..10).map {|x| x+1} #=> [6, 7, 8, 9, 10, 11]
• (5..10).reduce(:+) #=> 45
Google MapReduce

• Modeled after map() and reduce()
• Programming model
• Programs are trivially parallelizable
Demo time!
Gisting::Spec
input.file_pattern = quot;file.txtquot;
input.map do |map_input|
  words = map_input.strip.split(quot;tquot;)
  Emit(words[1], quot;1quot;)
end
output.reduce do |reduce_input|
  count = 0
  reduce_input.each do |value|
    count += value.to_i
  end
  Emit(count)
end
inputs = args
spec = Gisting::Spec.new
inputs.each do |file_input|
  input = spec.add_input
  input.file_pattern = file_input
  input.map do |map_input|
    # 2722
 mailbox
 2006-05-23 00:08:39
    words = map_input.strip.split(quot;tquot;)
    Emit(words[1], quot;1quot;)
  end
end
output = spec.output
output.filebase = quot;/Users/mchung/Public/datasets/outputquot;
output.num_tasks = 2
output.reduce do |reduce_input|
  count = 0
  reduce_input.each do |value|
    count += value.to_i
  end
  Emit(count)
end

result = MapReduce(spec)
pp result
Gisting

• MapReduce programming model in Ruby
• Uses ruby2ruby to serialize procs
• Uses EventMachine for Map/ReduceServer
•   -: 94978
•   mailbox: 20872
•   google: 6758
•   ebay: 2832
•   yahoo: 2674
•   yahoo.com: 2198
•   myspace.com: 1916
•   google.com: 1882
self.give(:thanks)
                  OpenRain
               openrain.com

                 My Git Repo
          github.com/mchung

                 Marc Chung
         blog.marcchung.com

                   Ruby::AZ
                  rubyaz.org
Resources
Code Generation: The Safety Scissors Of Metaprogramming
       mwrc2008.confreaks.com/03bowkett.html

       Forbidden Fruit: A Taste of Ruby's Parse Tree
      goruco2008.confreaks.com/03_wanstrath.html

                       Ruby2Ruby
           seattlerb.rubyforge.org/ruby2ruby/

                        ParseTree
                 parsetree.rubyforge.org

Más contenido relacionado

La actualidad más candente

Puppet Module Reusability - What I Learned from Shipping to the Forge
Puppet Module Reusability - What I Learned from Shipping to the ForgePuppet Module Reusability - What I Learned from Shipping to the Forge
Puppet Module Reusability - What I Learned from Shipping to the Forge
Puppet
 
marko_go_in_badoo
marko_go_in_badoomarko_go_in_badoo
marko_go_in_badoo
Marko Kevac
 

La actualidad más candente (20)

Crystal: Fundamentos, objetivos y desafios - Cacic 2019
Crystal: Fundamentos, objetivos y desafios - Cacic 2019Crystal: Fundamentos, objetivos y desafios - Cacic 2019
Crystal: Fundamentos, objetivos y desafios - Cacic 2019
 
Hijacking Ruby Syntax in Ruby
Hijacking Ruby Syntax in RubyHijacking Ruby Syntax in Ruby
Hijacking Ruby Syntax in Ruby
 
Puppet Module Reusability - What I Learned from Shipping to the Forge
Puppet Module Reusability - What I Learned from Shipping to the ForgePuppet Module Reusability - What I Learned from Shipping to the Forge
Puppet Module Reusability - What I Learned from Shipping to the Forge
 
marko_go_in_badoo
marko_go_in_badoomarko_go_in_badoo
marko_go_in_badoo
 
Groovy on the Shell
Groovy on the ShellGroovy on the Shell
Groovy on the Shell
 
How to make a large C++-code base manageable
How to make a large C++-code base manageableHow to make a large C++-code base manageable
How to make a large C++-code base manageable
 
Minicurso Ruby e Rails
Minicurso Ruby e RailsMinicurso Ruby e Rails
Minicurso Ruby e Rails
 
Working with databases in Perl
Working with databases in PerlWorking with databases in Perl
Working with databases in Perl
 
PL/Perl - New Features in PostgreSQL 9.0
PL/Perl - New Features in PostgreSQL 9.0PL/Perl - New Features in PostgreSQL 9.0
PL/Perl - New Features in PostgreSQL 9.0
 
On UnQLite
On UnQLiteOn UnQLite
On UnQLite
 
How to Develop Puppet Modules: From Source to the Forge With Zero Clicks
How to Develop Puppet Modules: From Source to the Forge With Zero ClicksHow to Develop Puppet Modules: From Source to the Forge With Zero Clicks
How to Develop Puppet Modules: From Source to the Forge With Zero Clicks
 
A Life of breakpoint
A Life of breakpointA Life of breakpoint
A Life of breakpoint
 
How to Write Node.js Module
How to Write Node.js ModuleHow to Write Node.js Module
How to Write Node.js Module
 
RestMQ - HTTP/Redis based Message Queue
RestMQ - HTTP/Redis based Message QueueRestMQ - HTTP/Redis based Message Queue
RestMQ - HTTP/Redis based Message Queue
 
Profiling and optimizing go programs
Profiling and optimizing go programsProfiling and optimizing go programs
Profiling and optimizing go programs
 
Py conkr 20150829_docker-python
Py conkr 20150829_docker-pythonPy conkr 20150829_docker-python
Py conkr 20150829_docker-python
 
Ruby meets Go
Ruby meets GoRuby meets Go
Ruby meets Go
 
The Art of JVM Profiling
The Art of JVM ProfilingThe Art of JVM Profiling
The Art of JVM Profiling
 
Stop Monkeys Fall
Stop Monkeys FallStop Monkeys Fall
Stop Monkeys Fall
 
用 Go 語言打造多台機器 Scale 架構
用 Go 語言打造多台機器 Scale 架構用 Go 語言打造多台機器 Scale 架構
用 Go 語言打造多台機器 Scale 架構
 

Similar a Hacking with ruby2ruby

Rapid Development with Ruby/JRuby and Rails
Rapid Development with Ruby/JRuby and RailsRapid Development with Ruby/JRuby and Rails
Rapid Development with Ruby/JRuby and Rails
elliando dias
 
Migrating To Ruby1.9
Migrating To Ruby1.9Migrating To Ruby1.9
Migrating To Ruby1.9
tomaspavelka
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
David Padbury
 
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
Nick Sieger
 
Web aplikāciju izstrāde ar Ruby on Rails un Oracle DB
Web aplikāciju izstrāde ar Ruby on Rails un Oracle DBWeb aplikāciju izstrāde ar Ruby on Rails un Oracle DB
Web aplikāciju izstrāde ar Ruby on Rails un Oracle DB
Raimonds Simanovskis
 

Similar a Hacking with ruby2ruby (20)

Rapid Development with Ruby/JRuby and Rails
Rapid Development with Ruby/JRuby and RailsRapid Development with Ruby/JRuby and Rails
Rapid Development with Ruby/JRuby and Rails
 
Migrating To Ruby1.9
Migrating To Ruby1.9Migrating To Ruby1.9
Migrating To Ruby1.9
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
All I Need to Know I Learned by Writing My Own Web Framework
All I Need to Know I Learned by Writing My Own Web FrameworkAll I Need to Know I Learned by Writing My Own Web Framework
All I Need to Know I Learned by Writing My Own Web Framework
 
Quick Intro To JRuby
Quick Intro To JRubyQuick Intro To JRuby
Quick Intro To JRuby
 
Impacta - Show Day de Rails
Impacta - Show Day de RailsImpacta - Show Day de Rails
Impacta - Show Day de Rails
 
Intro to J Ruby
Intro to J RubyIntro to J Ruby
Intro to J Ruby
 
Groovy
GroovyGroovy
Groovy
 
Toolbox of a Ruby Team
Toolbox of a Ruby TeamToolbox of a Ruby Team
Toolbox of a Ruby Team
 
Ruby on Rails Presentation
Ruby on Rails PresentationRuby on Rails Presentation
Ruby on Rails Presentation
 
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
 
Learning From Ruby (Yapc Asia)
Learning From Ruby (Yapc Asia)Learning From Ruby (Yapc Asia)
Learning From Ruby (Yapc Asia)
 
Groovy a Scripting Language for Java
Groovy a Scripting Language for JavaGroovy a Scripting Language for Java
Groovy a Scripting Language for Java
 
Ruby Isn't Just About Rails
Ruby Isn't Just About RailsRuby Isn't Just About Rails
Ruby Isn't Just About Rails
 
Web aplikāciju izstrāde ar Ruby on Rails un Oracle DB
Web aplikāciju izstrāde ar Ruby on Rails un Oracle DBWeb aplikāciju izstrāde ar Ruby on Rails un Oracle DB
Web aplikāciju izstrāde ar Ruby on Rails un Oracle DB
 
Performance Profiling in Rust
Performance Profiling in RustPerformance Profiling in Rust
Performance Profiling in Rust
 
Ugo Cei Presentation
Ugo Cei PresentationUgo Cei Presentation
Ugo Cei Presentation
 
mongodb-introduction
mongodb-introductionmongodb-introduction
mongodb-introduction
 
Developing cross platform desktop application with Ruby
Developing cross platform desktop application with RubyDeveloping cross platform desktop application with Ruby
Developing cross platform desktop application with Ruby
 
TDC 2012 - Patterns e Anti-Patterns em Ruby
TDC 2012 - Patterns e Anti-Patterns em RubyTDC 2012 - Patterns e Anti-Patterns em Ruby
TDC 2012 - Patterns e Anti-Patterns em Ruby
 

Último

Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Último (20)

Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 

Hacking with ruby2ruby