rapid development with ruby/jruby and rails

Post on 15-May-2015

1.625 Views

Category:

Technology

4 Downloads

Preview:

Click to see full reader

TRANSCRIPT

1

Rapid Development with Ruby/JRuby and RailsLee Chuk MunnStaff EngineerSun Microsystems

1

2

Why Ruby?

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/, "after")> Maybe dynamic typing /duck typing

• Design to put the “fun” back into programming

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

5

A Typical Ruby Classclass Song

@@plays = 0

attr_accessor :name, :artist, :duration

def initialize(d, a, d)

@name = n; @artist = a; @duration = d

end

public

def duration_in_minutes

@duration / 60

end

def duration_in_minutes=(v)

@duration = (v * 60)

end

def play

@@plays += 1

puts "#{@name} plays #{@@plays}"

@@plays

end

end

Properties

Virtual properties

Constructor

No return

Interpolated values

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

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

bar

Symbol table

Memory location

foo:foo

8

attr_accessor :color, :age, :name

protected :deposit, :withdrawl

color = {:red => 0xf00,:green => 0x0f0,:blue => 0x00f

}

add_column :plugins, :price, :decimal, :precision => 8, :scale => 2, :default => 0

Example Use of SymbolsAttribute

Access modifiers

Maps

As keyword parameters

9

Everything Returns a Value• Returned not required

• Statements can be used as expressions

• Even defining a method has a return value> Returns nil

def duration_in_minutes@duration / 60

end

gt = if (x > y) true else false

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

11

Customization with Closureclass ColorButton

attr_accessor :label, :r, :g, :bdef initialize(l)

label = 1r = 0x0fg = 0x0fb = 0x0fif block_given?

yield selfend

end b = ColorButton(“Press me”) do |button|button.r = 0xff# more stuff...

end

12

Common Uses of Closures• Iteration

• Resource management

• Callbacks

• Initialization

From http://onestepback.org/articles/10things/item3.html

[1,2,3].each {|i| puts i }

File.new("/etc/hosts", "r").each {|e| puts e }

widget.on_button_press { puts "Button Press" }

a = Array.new(5) {|i| i * i }

13

Almost Everything is a Method Call• In lots of cases, invoking method without knowing it

• 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

array[i] = 0 – invoking the [] method1 + 2 + 3 – 1.+(2.+(3))str.length

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

is to send a '+' message with one value

• Use respond_to? to find out if an object knows how to handle a message

obj.send(:method, param)

1 + 2 + 31.send(:+, 2.send(:+, 3))

1.respond_to? :succ => true

15

So What Is the Big Deal?public VCR

def initialize@messages = []

enddef method_missing(method, *args, &block)

@messages << [method, args, block]enddef play_back_to(obj)

@messages.each do |method, args, block|obj.send(method, *args, &block)

endend

end From http://onestepback.org/articles/10things/page017.html

varag

Push triplet onto array

16

Example of Macro at the Language Level

vcr = VCR.newvcr.sub!(/Java/) { |match| match.reverse }vcr.upcase!vcr[11,5] = "Universe"vcr << "!"

string = "Hello Java World"puts string

vcr.play_back_to(string)puts string # => "Hello AVAJ Universe"

Capture a group of operations. Reapply these on a separate object

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.newputs d.quack if d.responds_to :quack

18

Reuse – Inheritance • Supports inheritance

class KaraokeSong < Song...def to_s

super + “[#{@lyrics}]”end

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

20

Mixin Examplemodule Stringify

def stringifyif @value == 1

"One"elsif @value == 2

"Two"elsif @value == 3

"Three"end

endend

class MyNumber include Stringifydef initialize(value)

@value = valueend...

Stringify example http://www.juixe.com/techknow/index.php/2006/06/15/mixins-in-ruby/

21

Reuse – Modifying Existing Class• Methods can be added to a class at any time> Applies to built in classes

• Can be frozen

class Stringdef rot13

self.tr("A-Ma-mN-Zn-z","N-Zn-zA-Ma-m")end

end

“hello world”.rot13 #=> uryyb jbeyq

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

23

Example of Ruby's Malleabilityclass Foo

def method_missing(name, *args)if args[0].is_a?(Proc)

self.class.instance_eval dodefine_method(name.to_s.chomp("="), args[0])

endelse

superend

endend

Adapted from http://tech.rufy.com/2006/08/dynamically-add-methods-to-classes.html

f = Foo.newf.greet = lambda {|t| "Hello #{t}!"}f.greet "Hello SunTech Days"

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

25

DSL ExamplePBJ Sandwich

ingredients:- two slices of bread- one tablespoon of peanut butter- one teaspoon of jam

instructions:- spread peanut butter on bread- spread jam on top of peanut butter- place other slice of bread on top

servings: 1prep time: 2 minutes

recipe "PBJ Sandwich"

ingredients :bread 2.sliceingredients :peanut_butter 1.spooningredients :jam 1.teaspoon instructions do

step 1 “spread peanut butter”step 2 “spread jam...”step 3 “place other slice...”

end

servings 1prep_time 2.minutes

Adapted from http://weblog.jamisbuck.org/2006/4/20/writing-domain-specific-languages

26

This is great, but...• Ruby language is different from Java• Ruby platform is different from Java• How can Java developers benefit?

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

28

FreeTTS Example• In Java

VoiceManager vm = VoiceManager.getInstance();Voice voice = vm.getVoice("kevin16"); voice.allocate();voice.speak(jTextArea1.getText());voice.deallocate();

• In Rubyrequire 'java'vm = com.sun.speech.freetts.VoiceManager.getInstance()voice = vm.getVoice("kevin16")voice.allocate()voice.speak("Calling Java code from Ruby")voice.deallocate()

• JRuby engine available through JSR-223 in JavaSE 6

29

Rapid Development with Ruby/JRuby and RailsLee Chuk MunnStaff EngineerSun Microsystems

29

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 inthe Slide Sorter.

● To insert an entire presentation, select Insert>File.

31

Template – Text Slidewith Two Line Title and Subtitle

• 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.

This is a Subtitle with Initial Caps Each Major Word

32

GlassFish V2

33

34

35

36

37

38

39

40

41

42

43

44

45

Title HereLee Chuk MunnStaff EngineerSun Microsystems

45

top related