Using a text record from the database as a Java String?

I’m building a rails app where the user input is submitted to the
database via a text field, with :text datatype. I want to take this text
data and use java to analyse and interact with it, but to do this it
obviously needs to be a String datatype. Is there an easy way to cast
the text data to a String so that I can manipulate it using Java? Thanks
:slight_smile:

Its been quite some time since I have used Rails so I am not 100%
certain
but I thought ActiveRecord simply treated the DB text data type as if it
were a string in memory and everything should just “work”. According to

"When calling Java from JRuby, primitive Ruby types are converted to
default boxed Java types:
Ruby TypeJava Type*"foo"java.lang.String1java.lang.Long1.0*
java.lang.Doubletrue, falsejava.lang.Boolean**1
java.math.BigInteger

If you are running into a problem there is always “to_java” but JRuby
should already be converting the object on your behalf:

=====
irb(main):001:0> s = “ruby string”

=> “ruby string”

irb(main):002:0> j = s.to_java

=> #Java::JavaLang::String:0x79cda784

irb(main):006:0> j.last_index_of(‘r’)

=> 7

HTH,
Ariel

Ariel V.
e-mail: [email protected]
website: http://blog.arielvalentin.com
skype: ariel.s.valentin
twitter: arielvalentin
linkedin: Sign Up | LinkedIn

*simplicity *communication
*feedback *courage *respect

Below is a JRuby irb session that proves Ariel’s point. A Ruby string
is
passed to the constructor of java.util.Locale, a Java method requiring a
Java string. The object is successfully created, proving that the Ruby
string was converted to a Java string when calling the Java method:

jruby-1.7.15 :001 > import java.util.Locale
=> [Java::JavaUtil::Locale]
jruby-1.7.15 :002 > s = ‘en_US’
=> “en_US”
jruby-1.7.15 :003 > s.class
=> String
jruby-1.7.15 :004 > locale = java.util.Locale.new(s)
=> #Java::JavaUtil::Locale:0x5a670b0b

  • Keith

On Thu, Oct 23, 2014 at 9:27 AM, Ariel V.
[email protected]