Module: Persistable::InstanceMethods

Included in:
ModernFall, ModernRise, StandardFall, StandardRise
Defined in:
lib/mtg_card_finder/concerns/persistable.rb

Instance Method Summary collapse

Instance Method Details

#attribute_values_for_sql_checkObject



178
179
180
181
182
# File 'lib/mtg_card_finder/concerns/persistable.rb', line 178

def attribute_values_for_sql_check
  self.class.attributes.keys[1..-1].collect {|attr_names| self.send(attr_names)}
  #I go through the key names (minus 'id') and return an array containing their values for the recieving instance
  #basically like getting an array of getter methods for that instance
end

#insertObject



199
200
201
202
203
204
205
206
207
208
209
210
# File 'lib/mtg_card_finder/concerns/persistable.rb', line 199

def insert
  sql = "      INSERT INTO \#{self.class.table_name} (\#{self.class.attributes_names_insert_sql}) VALUES (\#{self.class.question_marks_insert_sql})\n  SQL\n\n  #using splat operator to signify that there may be more than one argument in terms of attr_readers\n  DB[:conn].execute(sql, *attribute_values_for_sql_check)\n  #after inserting the card to the database, I want to get the primary key that is auto assigned to it\n  #from sql and set it to the instance method 'id' of this very instance variable.\n  self.id = DB[:conn].execute(\"SELECT last_insert_rowid() FROM \#{self.class.table_name}\")[0][0]\n  #returns first array with the first value of the array (i.e. index 0)\nend\n"

#persisted?Boolean

Returns:

  • (Boolean)


184
185
186
187
# File 'lib/mtg_card_finder/concerns/persistable.rb', line 184

def persisted?
  #the '!!' double bang converts object into a truthy value statement
  !!self.id
end

#saveObject



172
173
174
175
176
# File 'lib/mtg_card_finder/concerns/persistable.rb', line 172

def save
  #if the card has already been saved, then call update method
  persisted? ? update : insert
  #if not call insert method instead
end

#updateObject



189
190
191
192
193
194
195
196
197
# File 'lib/mtg_card_finder/concerns/persistable.rb', line 189

def update
  #updates by the unique identifier of 'id'
  sql = "       UPDATE \#{self.class.table_name} SET \#{self.class.sql_columns_to_update} WHERE id=(?)\n  SQL\n\n  #using splat operator to signify that there may be more than one argument in terms of attr_readers\n  DB[:conn].execute(sql, *attribute_values_for_sql_check, self.id)\nend\n"