Because I couldn't find any good examples on using this plug-in
online, I played with it and found a few things out. They're
documented by example in the code below. (Until better documentation
exists, hopefully this will be archived by help someone else out.)
require 'sequel'
# Set up a test database. Note the 'species' column on pets.
DB = Sequel.sqlite
DB.create_table :owners do
primary_key :id
String :name
end
DB.create_table :pets do
primary_key :id
foreign_key :o_id, :owners
String :name
String :species
end
# Set up the models for the test.
class Owner < Sequel::Model
one_to_many :pets, key: :o_id
end
class Pet < Sequel::Model
plugin :single_table_inheritance, :species # column holding class
names
def sound; "WHUT"; end
end
class Cat < Pet
def sound; "hiss"; end
end
class Dog < Pet
def sound; "bark"; end
end
# Play with some test data
me = Owner.create(name:'me')
Pet.create name:'Fonk', o_id:me.id # Species set to
"Pet"
Pet.create name:'Fuzz', o_id:me.id, species:'Cat' # Species set to
"Cat"
Cat.create name:'Meow', o_id:me.id # Species set to
"Cat"
Dog.create name:'Woof', o_id:me.id # Species set to
"Dog"
Dog << { name:'Ruff', o_id:me.id } # Species left as
nil
# The association array is populated with correct instance types!
p me.pets
#=> [ #<Pet @values={:id=>1, :o_id=>1, :name=>"Fonk", :species=>"Pet"}
>,
#=> #<Cat @values={:id=>2, :o_id=>1, :name=>"Fuzz", :species=>"Cat"}
>,
#=> #<Cat @values={:id=>3, :o_id=>1, :name=>"Meow", :species=>"Cat"}
>,
#=> #<Dog @values={:id=>4, :o_id=>1, :name=>"Woof", :species=>"Dog"}
>,
#=> #<Pet @values={:id=>5, :o_id=>1, :name=>"Ruff", :species=>nil}>]
# It works even if you use the generic class to start with
p Pet[name:'Meow'], Cat[name:'Meow']
#=> #<Cat @values={:id=>3, :o_id=>1, :name=>"Meow", :species=>"Cat"}>
#=> #<Cat @values={:id=>3, :o_id=>1, :name=>"Meow", :species=>"Cat"}>
# Asking the subclass, however, filters based on type
p Pet[name:'Ruff'], Dog[name:'Ruff']
#=> #<Pet @values={:id=>5, :o_id=>1, :name=>"Ruff", :species=>nil}>
#=> nil
# As may be obvious, this allows you to use custom methods per type
p Pet.all.map(&:sound)
#=> ["WHUT", "hiss", "hiss", "bark", "WHUT"]
--
You received this message because you are subscribed to the Google Groups
"sequel-talk" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/sequel-talk?hl=en.