Class: Pup::Model

Inherits:
Object show all
Extended by:
ColumnsBuilder, OrmMethods
Defined in:
lib/pup/model/model.rb

Class Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from OrmMethods

all, create, destroy_all, find

Constructor Details

#initializeModel

Returns a new instance of Model.



12
13
# File 'lib/pup/model/model.rb', line 12

def initialize
end

Class Attribute Details

.fieldsObject (readonly)

Returns the value of attribute fields.



74
75
76
# File 'lib/pup/model/model.rb', line 74

def fields
  @fields
end

.table_nameObject (readonly)

Returns the value of attribute table_name.



74
75
76
# File 'lib/pup/model/model.rb', line 74

def table_name
  @table_name
end

Class Method Details

.columns_arrayObject



93
94
95
# File 'lib/pup/model/model.rb', line 93

def columns_array
  @columns_array ||= fields.keys
end

.create_tableObject



87
88
89
90
91
# File 'lib/pup/model/model.rb', line 87

def create_table
  query = "CREATE TABLE IF NOT EXISTS #{@table_name}"\
          "(#{fields_builder(@fields)})"
  DB.execute(query)
end

.property(field_name, options = {}) ⇒ Object



82
83
84
85
# File 'lib/pup/model/model.rb', line 82

def property(field_name, options = {})
  @fields[field_name] = options
  attr_accessor field_name
end

.to_table(table_name) ⇒ Object



76
77
78
79
80
# File 'lib/pup/model/model.rb', line 76

def to_table(table_name)
  @table_name = table_name.to_s
  @fields = {}
  property :id, type: :integer, primary_key: true
end

Instance Method Details

#destroyObject



40
41
42
# File 'lib/pup/model/model.rb', line 40

def destroy
  DB.execute("DELETE FROM #{self.class.table_name} WHERE id= ?", id)
end

#saveObject



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/pup/model/model.rb', line 15

def save
  if id
    query = "UPDATE #{self.class.table_name} "\
            "SET #{update_field_set} "\
            "WHERE id = ?"
    DB.execute(query, table_values, id)
  else
    query = "INSERT INTO #{self.class.table_name} "\
            "(#{table_fields}) "\
            "VALUES(#{values_placeholders})"
    DB.execute(query, table_values)

    self.id = DB.execute("SELECT last_insert_rowid()")
  end
  self.class.find(id)
end

#update(parameters) ⇒ Object



32
33
34
35
36
37
38
# File 'lib/pup/model/model.rb', line 32

def update(parameters)
  parameters.each do |key, value|
    send("#{key}=", value)
  end

  save
end