metrix
metrix

Reputation: 1576

Extending Ruby Sequel

I am trying to make a library that will handle database connections by extending the Sequel object/module. but I have not been able to get passed this:

require 'sequel'
class Database 
  include Sequel
  def connect()
    self.ado(:conn_string=>"Server=homeServer;Provider=SQLNCLI10;Database=test;Trusted_Connection=yes;")
  end
end
db = LocalDatabase.new()
db.connect()

I get the following error: test.rb:5:in connect': undefined methodado' for # (NoMethodError) from test.rb:10:in `'

Why can't I see the ado method?

Upvotes: 1

Views: 546

Answers (2)

Jeremy Evans
Jeremy Evans

Reputation: 12139

In ruby, if you subclass a class, you can call the superclass's singleton methods by calling them as singleton methods of the subclass, but that does not work for included/extended modules. This is one way where modules differ from classes in terms of method lookup. To understand why, you'll need to read the details on how ruby's method lookup and object model works.

To call singleton methods of the Sequel module, you need to call them with an explicit receiver:

require 'sequel'
class Database 
  include Sequel
  def connect()
    Sequel.ado(:conn_string=>"Server=homeServer;Provider=SQLNCLI10;Database=test;Trusted_Connection=yes;")
  end
end
db = LocalDatabase.new()
db.connect()

FWIW, I don't recommend using the ado adapter except for read only workloads. Since you appear to be connecting to SQL Server, I recommend using the tinytds adapter.

Upvotes: 2

RadBrad
RadBrad

Reputation: 7304

What's happening is that the Sequel is being included so it's methods are available as instance methods, I think you want to extend, i.e.

require 'sequel'
class Database 
  extend Sequel
  def connect()
    ado(:conn_string=>
    "Server=homeServer;Provider=SQLNCLI10;Database=test;Trusted_Connection=yes;")
  end
end
db = LocalDatabase.new()
db.connect()

Upvotes: -1

Related Questions