itang / todo.itang.me

4 stars 2 forks source link

Ruby (JRuby) 实践 [进行中] #25

Open itang opened 10 years ago

itang commented 10 years ago

204-08-17 12:00 : 第60 页

204-08-17 16:12 : 第98 页

  1. [ ] 用ruby实现一键下载更新Your Github-Star-Repos

    文章

Time::now | Time::new
$ ruby -e 'puts Time.now'

找类 classpath

JRuby supports -I for Ruby code, naturally, but also understands Java’s -cp / -classpath option for Java classes:

命令行:

-I

ruby -I/path/to/library my_program.rb

-J-cp

jruby -J-cp /path/to/library.jar

环境变量:

JRuby supports RUBYOPT for finding Ruby code, and the Java equivalent ( CLASSPATH ) for finding Java classes

Ruby全局变量:

As an alternative or a supplement to the command-line classpath, you can add a . jar or directory to the $CLASSPATH variable inside Ruby itself (much as you’re used to doing with $LOAD_PATH or $: for Ruby libraries):

$CLASSPATH << '/usr/local/lib/jemmy/jemmy.jar'
require '/usr/local/lib/jemmy/jemmy.jar'

Both the -I argument and the $LOAD_PATH vari-able work on both Ruby and Java libraries in JRuby:

jruby -I/path/to -e "require 'library.jar' ..."

$LOAD_PATH << '/usr/local/lib/jemmy'
require 'jemmy.jar'

加载类

Ruby code will see Java packages as Ruby modules

The most reliable way to refer to a Java class in JRuby is by tacking Java:: onto the beginning of the full package name

  millis = Java::java.util.concurrent.TimeUnit::SECONDS.toMillis(10)
  puts "java.util.concurrent.TimeUnit::SECONDS.toMillis(10): #{millis}"

default package:

Java::MyTopLevelClass

JRuby provides top-level functions like com , org , java , and javax .

  puts java.util.Date.new

导入类(By Importing)

A common con-vention is to define a new constant consisting of just the class name

  sb = StringBuffer.new("hello")
  sb.append ", world"
  puts sb

Ruby provides a handy java_import shortcut that does exactly this kind of assignment

java_import java.lang.StringBuffer
java_import 'java.lang.StringBuffer'
['Frame' , 'Dialog' , 'Button' ].each do |name|
  java_import "org.netbeans.jemmy.operators.J#{name}Operator"
end
java_import 'java.lang.String' do |pkg, cls|
  puts "#{cls} lives in #{pkg}"
  'JString' # don't clobber Ruby's String class
end

使用对象

Static Methods

java_import java.lang.System
System.currentTimeMillis
System.current_time_millis

Static Fields

treat the field like a Ruby class-level method, calling it with dot notation and a Ruby-style snake_case name

java_import java.util.logging.Logger
java_import java.util.logging.Level
Logger.global.log Level::SEVERE, "It looks like you're writing a letter!"

对象构造(Object Construction)