Question

I am using Ruby with Sinatra and Sequel. Now I am trying to create classes for my project, for example the class "User" which should contain "First Name" and "Lastname". When creating an instance of that class it should be possible to directly set the names like new User("Some","name"). I am using Sequel to connect to a database and create a class::model like this:

class User < Sequel::Model end

My question is now where would I add a constructor for my class User and define all the variables? As I allready have the Sequel::Model "User" I can not create another class "User" but I can on the other hand not add a constructor to the Sequel::Model class because that would create a new dataset for each instance of the User class, wouldn´t it? I am confused.

If that was a bit difficult to understand here the short version: I have a file containing a class "User" which inherits Sequel::Model. Where would I put the class variables like name or id and methods like "do_something_with_a_specific_user()"?

Was it helpful?

Solution

Where would I put the class variables like name or id and methods like …

For attributes that are in the table, you don't. When the database is loaded, the User class will be built using information inferred from the users table in the database. If you have an id field, then model instances will get an id attribute etc etc. If you need extra attributes that aren't in the table, by all means just add them in the usual way. Same goes for methods.

Also, the syntax you'd use to create a new model instance would be more like user = User.new name: "php", lastname: "heini"

See http://sequel.jeremyevans.net/rdoc/files/README_rdoc.html#label-Sequel+Models


Be careful with the word "create" when talking about models, because there is creation of a record in the database and creation of an instance, but most people would expect "create" to refer to the first, not (only) the last. new is a good synonym for "create", hence it leads to a new record in the database (if you save it, otherwise just use create). If you want to get an instance (i.e. a record) then either capture the instance when calling new, or retrieve an existing record. There are plenty of ways to retrieve records, but [] is one you'll use a lot. It makes sense as a choice, since arrays and hashes use that syntax for record retrieval too.

class User < Sequel::Model

  def fullname
    "#{self.firstname} #{self.lastname}"
  end
end

# add your first user
u1 = User.new firstname: "Bill", lastname: "Flowerpot"

u1.fullname
# => "Bill Flowerpot"

u1.save

u1.id
# => 1

# retrieve it later by index
u1 = User[1]

# Retrieve a user (that has already been added to the db)
# by some other unique value
u2 => User[firstname: "Ben"]
u2.fullname
# => "Ben Flowerpot"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top