Rapid Development with Ruby/JRuby and Rails

1,840 views

Published on

Published in: Technology
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
1,840
On SlideShare
0
From Embeds
0
Number of Embeds
6
Actions
Shares
0
Downloads
49
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

Rapid Development with Ruby/JRuby and Rails

  1. 1. Rapid Development with Ruby/JRuby and Rails Lee Chuk Munn Staff Engineer Sun Microsystems 1
  2. 2. Why Ruby? 2
  3. 3. What is Ruby? • Created by Yukihiro “Matz” Matsumoto > Started around 1993, about the same time as Java • What is a scripting language? > No compilation unit puts “Hello world” > Not compiled > Specialized syntax and data types subject.gsub(/before/, quot;afterquot;) > Maybe dynamic typing /duck typing • Design to put the “fun” back into programming 3
  4. 4. Ruby Conventions • ClassNames • methods_names, variable_names • visible? • methods_with_side_effects! • @instance_variable • @@class_variable • $global_variable • A_CONSTANT, AnotherConstant • MyClass.class_method – doc only • MyClass#instance_method – doc only 4
  5. 5. A Typical Ruby Class class Song Properties @@plays = 0 attr_accessor :name, :artist, :duration def initialize(d, a, d) @name = n; @artist = a; @duration = d end Constructor public def duration_in_minutes @duration / 60 No return end Virtual properties def duration_in_minutes=(v) @duration = (v * 60) end Interpolated values def play @@plays += 1 puts quot;#{@name} plays #{@@plays}quot; @@plays end 5 end
  6. 6. Sample Execution s = Song.new(“Cavatina”, “John Williams”, 200) puts(“duration: #{s.duration}”) puts “in mins: #{s.duration_in_minutes}” s.duration_in_minutes = 4 puts “in mins: #{s.duration}” s.play 6
  7. 7. Symbols • :a_name is symbol, think identities > Refer to the name a_name, not the value that a_name may potentially hold • Typically used in maps, property declaration, method names, any place you need a name/symbol :foo foo Symbol table foo Memory location bar 7
  8. 8. Example Use of Symbols attr_accessor :color, :age, :name Attribute protected :deposit, :withdrawl Access modifiers color = { :red => 0xf00, Maps :green => 0x0f0, :blue => 0x00f As keyword parameters } add_column :plugins, :price, :decimal, :precision => 8, :scale => 2, :default => 0 8
  9. 9. Everything Returns a Value • Returned not required def duration_in_minutes @duration / 60 end • Statements can be used as expressions gt = if (x > y) true else false • Even defining a method has a return value > Returns nil 9
  10. 10. Everything Is An Object • 'Primitives' are objects > -1.abs • nil is an object > nil.methods • Classes are objects > Song.new – invoking the new method on 'Song' object > Create instances of themselves • Code blocks are objects > They can be pass around, even as parameters > Blocks can be closure 10
  11. 11. Customization with Closure class ColorButton attr_accessor :label, :r, :g, :b def initialize(l) label = 1 r = 0x0f g = 0x0f b = 0x0f if block_given? yield self end end b = ColorButton(“Press me”) do |button| button.r = 0xff # more stuff ... end 11
  12. 12. Common Uses of Closures • Iteration [1,2,3].each {|i| puts i } • Resource management File.new(quot;/etc/hostsquot;, quot;rquot;).each {|e| puts e } • Callbacks widget.on_button_press { puts quot;Button Pressquot; } • Initialization a = Array.new(5) {|i| i * i } From http://onestepback.org/articles/10things/item3.html 12
  13. 13. Almost Everything is a Method Call • In lots of cases, invoking method without knowing it array[i] = 0 – invoking the [] method 1 + 2 + 3 – 1.+(2.+(3)) str.length • Methods can be invoked with or without parenthesis > Most developers chose the latter > Code looks more natural especially if you are doing DSL • Methods can be overridden > Get operator overloading for free 13
  14. 14. Every Method Call is a Message • obj.method(param) means having a method on the object in Java • In Ruby, this means sending a message to the object obj.send(:method, param) is to send a '+' message with one value 1+2+3 1.send(:+, 2.send(:+, 3)) • Use respond_to? to find out if an object knows how to handle a message 1.respond_to? :succ => true 14
  15. 15. So What Is the Big Deal? public VCR def initialize varag @messages = [] end def method_missing(method, *args, &block) @messages << [method, args, block] end Push triplet onto array def play_back_to(obj) @messages.each do |method, args, block| obj.send(method, *args, &block) end end end From http://onestepback.org/articles/10things/page017.html 15
  16. 16. Example of Macro at the Language Level vcr = VCR.new vcr.sub!(/Java/) { |match| match.reverse } vcr.upcase! Capture a group of vcr[11,5] = quot;Universequot; operations. Reapply vcr << quot;!quot; these on a separate object string = quot;Hello Java Worldquot; puts string vcr.play_back_to(string) puts string # => quot;Hello AVAJ Universequot; 16
  17. 17. Duck Typing Instead of Interfaces • Familiar with the idea of using interface to enforce contracts > An object can only be considered a thread if it implements Runnable • If an object can behave like a thread, then should be considered as a thread > Runnable is irrelevant if it has run() > If it walks like a duck, talks like a duck, then we can treat it as a duck d = DuckLikeObject.new puts d.quack if d.responds_to :quack 17
  18. 18. Reuse – Inheritance • Supports inheritance class KaraokeSong < Song ... def to_s super + “[#{@lyrics}]” end 18
  19. 19. Reuse - Mixins • Multiple inheritance like mechanism call mixins defined by modules > A namespace > Can have methods > But cannot be instantiated • Becomes part of a class when included a module is included in a class > The reverse is also possible by extending the module with an object 19
  20. 20. Mixin Example module Stringify class MyNumber def stringify include Stringify if @value == 1 def initialize(value) quot;Onequot; @value = value elsif @value == 2 end quot;Twoquot; ... elsif @value == 3 quot;Threequot; end end end Stringify example http://www.juixe.com/techknow/index.php/2006/06/15/mixins-in-ruby/ 20
  21. 21. Reuse – Modifying Existing Class • Methods can be added to a class at any time > Applies to built in classes • Can be frozen class String def rot13 self.tr(quot;A-Ma-mN-Zn-zquot;,quot;N-Zn-zA-Ma-mquot;) end end “hello world”.rot13 #=> uryyb jbeyq 21
  22. 22. Extremely Flexible and Dynamic • One of the hallmarks of scripting languages • Metaprogramming – programs that write or manipulate themselves • Some of the stuff you can do > Trap missing methods and add them if you so desire > Kernel definition hooks eg. Adding a method > Create code and execute them on the fly 22
  23. 23. Example of Ruby's Malleability class Foo def method_missing(name, *args) if args[0].is_a?(Proc) self.class.instance_eval do define_method(name.to_s.chomp(quot;=quot;), args[0]) end else super end end f = Foo.new end f.greet = lambda {|t| quot;Hello #{t}!quot;} f.greet quot;Hello SunTech Daysquot; Adapted from http://tech.rufy.com/2006/08/dynamically-add-methods-to-classes.html 23
  24. 24. DSLs with Ruby • DSL is a language designed for a specific domain > Captures jargon in language • Ruby's DSL is internal (Fowler) > Morph language into DSL > Java is external and/or API based • Killer features for DSL with Ruby > Paranthesis-less method invocation > Closures > Malleable and dynamc engine > Variable argument list > Symbols 24
  25. 25. DSL Example PBJ Sandwich recipe quot;PBJ Sandwichquot; ingredients: ingredients :bread 2.slice - two slices of bread ingredients :peanut_butter 1.spoon - one tablespoon of peanut butter ingredients :jam 1.teaspoon - one teaspoon of jam instructions do step 1 “spread peanut butter” instructions: step 2 “spread jam...” - spread peanut butter on bread step 3 “place other slice...” - spread jam on top of peanut butter end - place other slice of bread on top servings 1 prep_time 2.minutes servings: 1 prep time: 2 minutes Adapted from http://weblog.jamisbuck.org/2006/4/20/writing-domain-specific-languages 25
  26. 26. This is great, but... • Ruby language is different from Java • Ruby platform is different from Java • How can Java developers benefit? 26
  27. 27. JRuby • Implementation of Ruby written in Java • Compatible with Ruby 1.8.6 • Enables use of Java code in Ruby • Easier deployment • More libraries • More platforms • Less “political” resistence 27
  28. 28. FreeTTS Example • In Java VoiceManager vm = VoiceManager.getInstance(); Voice voice = vm.getVoice(quot;kevin16quot;); voice.allocate(); voice.speak(jTextArea1.getText()); voice.deallocate(); • In Ruby require 'java' vm = com.sun.speech.freetts.VoiceManager.getInstance() voice = vm.getVoice(quot;kevin16quot;) voice.allocate() voice.speak(quot;Calling Java code from Rubyquot;) voice.deallocate() • JRuby engine available through JSR-223 in JavaSE 6 28
  29. 29. Rapid Development with Ruby/JRuby and Rails Lee Chuk Munn Staff Engineer Sun Microsystems 29
  30. 30. 3. Inserting New or Existing Slides ● To add a new slide to your presentation, select Insert>Slide. You can also duplicate slides in the Slide Sorter using copy and paste. ● To add a slide(s) from another presentation, copy and paste from one file to the other in the Slide Sorter. ● To insert an entire presentation, select Insert>File. 30
  31. 31. Template – Text Slide with Two Line Title and Subtitle This is a Subtitle with Initial Caps Each Major Word • To insert a Subtitle on other slides, copy and paste the Subtitle text block • On a slide with a two line Title and Subtitle (as shown here) move the bullet text block down to make room for the Subtitle. You can also duplicate this slide and replace the content. 31
  32. 32. GlassFish V2 32
  33. 33. 33
  34. 34. 34
  35. 35. 35
  36. 36. 36
  37. 37. 37
  38. 38. 38
  39. 39. 39
  40. 40. 40
  41. 41. 41
  42. 42. 42
  43. 43. 43
  44. 44. 44
  45. 45. Title Here Lee Chuk Munn Staff Engineer Sun Microsystems 45

×