调用方法而不传递参数

时间:2017-12-19 05:44:38

标签: ruby ldap openldap

这是我的代码

require 'rubygems'
require 'net/ldap'

class LdapUser
    def create_connection
       ldap = Net::LDAP.new
       ldap.host = 'localhost'
       ldap.port = 389
       puts "****** Conncection result ********"
       puts ldap.get_operation_result 
       return ldap
   end

  # only admin can authenticate
  def authenticate(ldap)
       ldap.authenticate "cn=admin,dc=example,dc=com",'123'  
  end
user = LdapUser.new
ldap=user.create_connection
user.authenticate(ldap)

我想使用对象调用authenticate而不传递ldap作为参数。

有没有办法做到这一点?有没有什么方法可以提高代码的效率和效率?

1 个答案:

答案 0 :(得分:1)

你可以这样做:

class LdapUser
  def ldap
    return @ldap if @ldap
    create_connection
  end

  # only admin can authenticate
  def authenticate
    ldap.authenticate "cn=admin,dc=example,dc=com",'123'  
  end

  private

  def create_connection
    @ldap = Net::LDAP.new
    @ldap.host = 'localhost'
    @ldap.port = 389
    puts "****** Conncection result ********"
    puts @ldap.get_operation_result 
    @ldap
  end
end

user = LdapUser.new
user.authenticate