0

I have following jruby code that uses java class javax.naming.InitialContext:

if RUBY_PLATFORM == "java"
  require 'java'
  import javax.naming.InitialContext

  module JndiProperties
    def self.getProperty(name)
      begin
        env.lookup(name).to_s
      rescue
        nil
      end
    end

    def self.[](name)
      getProperty(name)
    end

    private
    def self.env
      context = InitialContext.new
      environment = context.lookup 'java:comp/env'
      environment
    end
  end
else
  module JndiProperties
    def self.getProperty(name)
      nil
    end

    def self.[](name)
      getProperty(name)
    end
  end
end

I use this module in database.yml to configure database connection. E.g.:

username: <%= JndiProperties['ANTARCTICLE_DB_USER'] || 'root' %>

When I try to run rails application, i get uninitialized constant JndiProperties::InitialContext. If i try to use this module from irb, it will work as expected.

wedens
  • 1,782
  • 14
  • 18

1 Answers1

1

just put the import line into the module :

module JndiProperties
  java_import 'javax.naming.InitialContext'
end

as it uses const_missing to resolve or assign the constant manually :

InitialContext = Java::JavaxNaming::InitialContext

than it should work even outside the module

kares
  • 7,076
  • 1
  • 28
  • 38
  • same error.. maybe i need to clarify that i use warbler to pack my app into war file and then deploy it – wedens Aug 12 '13 at 18:22
  • @wedens than it must be something else interfering this simply work as expected https://gist.github.com/kares/d78d138165da7ad225b6 – kares Aug 13 '13 at 10:19
  • yes, it works in irb and as a script. but i can't get it to work inside war file (same error) – wedens Aug 13 '13 at 15:24
  • if you're sure that this code of yours gets loaded (and not just some other `JndiProperties` module part) I would consider reporting with Warbler/JRuby-Rack ... it would be best if you could reproduce on a minimal app that you can share. – kares Aug 15 '13 at 05:46