Module: DBStruct::DBStructClassMethods

Defined in:
lib/dbstruct.rb

Instance Method Summary collapse

Instance Method Details

#bind(fields) ⇒ Object

Use this to bind a class to a table, so new objects created with template will match fields in database



153
154
155
156
157
158
159
160
161
162
163
164
165
# File 'lib/dbstruct.rb', line 153

def bind(fields)
  
  if fields.empty?
    raise ArgumentError, "Trying to bind object to empty list of fields..."
  end
  
  if (@@_template rescue nil) != nil
    raise ArgumentError, "Class already bound to table: #{@@_template.to_s}. Use method rebind if new binding is needed", caller(1)
  end
  @@_template = {}
  fields.each { |field| @@_template[field] = nil} 
  return 
end

#bind_table(db, table) ⇒ Object

Binds class to given table in the database, Sequel specific



138
139
140
141
142
143
144
145
146
147
148
149
150
# File 'lib/dbstruct.rb', line 138

def bind_table(db,table)
  tablefields = []
  @@_table = table
  
  if db.schema(table).empty?
    raise ArgumentError, "Table [#{table}] was not found. Unable to bind object", caller(1)
  end
  
  db.schema(table).each do |fields|
    tablefields << fields[0] 
  end
  bind(tablefields)
end

#create(rows) ⇒ Object



119
120
121
122
123
124
125
126
127
128
129
130
# File 'lib/dbstruct.rb', line 119

def create(rows)
  list = []
  if rows == nil
    return list
  end
  rows.each do |row|
    the_instance = self.new
    the_instance.load(row)
    list << the_instance
  end
  list
end

#delete!(db, search_criteria) ⇒ Object



180
181
182
# File 'lib/dbstruct.rb', line 180

def delete!(db,search_criteria)
  db[@@_table].filter(search_criteria).delete
end

#find(db, search_criteria) ⇒ Object



175
176
177
# File 'lib/dbstruct.rb', line 175

def find(db,search_criteria)
  db[@@_table].filter(search_criteria)
end

#get_tableObject

Hack enable referencing modularized class-variable from instance



133
134
135
# File 'lib/dbstruct.rb', line 133

def get_table
  return @@_table
end

#rebind!(fields) ⇒ Object

Method can rebind fields if database changes dynamicly.… I’m not sure you should need this one.…



168
169
170
171
172
# File 'lib/dbstruct.rb', line 168

def rebind!(fields)
  @@_template = {}
  fields.each { |field| @@_template[field] = nil}
  return 
end

#template(*args) ⇒ Object



191
192
193
194
195
# File 'lib/dbstruct.rb', line 191

def template(*args)
  the_instance = self.new(*args)
  the_instance.load(@@_template)
  the_instance
end

#update!(db, search_criteria, update_criteria) ⇒ Object



185
186
187
# File 'lib/dbstruct.rb', line 185

def update!(db,search_criteria, update_criteria)
  db[@@_table ].filter(search_criteria).update(update_criteria)
end