Module: Persistence::ClassMethods
- Defined in:
- lib/bloc_record/persistence.rb
Instance Method Summary collapse
- #create(attrs) ⇒ Object
- #destroy(*id) ⇒ Object
- #destroy_all(conditions_hash = nil) ⇒ Object
- #update(ids, updates) ⇒ Object
- #update_all(updates) ⇒ Object
Instance Method Details
#create(attrs) ⇒ Object
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
# File 'lib/bloc_record/persistence.rb', line 10 def create(attrs) attrs = BlocRecord::Utility.convert_keys(attrs) attrs.delete "id" vals = attributes.map { |key| BlocRecord::Utility.sql_strings(attrs[key]) } connection.execute( "INSERT INTO #{table} (#{attributes.join(',')}) VALUES (#{vals.map {|x| '?'}.join(', ')})", vals ) data = Hash[attributes.zip attrs.values] data["id"] = connection.execute("SELECT last_insert_rowid();")[0][0] new(data) end |
#destroy(*id) ⇒ Object
50 51 52 53 54 55 56 57 58 59 60 61 62 |
# File 'lib/bloc_record/persistence.rb', line 50 def destroy(*id) if id.length > 1 where_clause = "WHERE id IN (#{id.join(",")});" else where_clause = "WHERE id = #{id.first};" end connection.execute <<-SQL DELETE FROM #{table} #{where_clause} SQL true end |
#destroy_all(conditions_hash = nil) ⇒ Object
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 |
# File 'lib/bloc_record/persistence.rb', line 64 def destroy_all(conditions_hash=nil) if conditions_hash && !conditions_hash.empty? conditions_hash = BlocRecord::Utility.convert_keys(conditions_hash) conditions = conditions_hash.keys.map { |key| "#{key} = ?" }.join(" and ") connection.execute( "DELETE FROM #{table} WHERE #{conditions};", conditions_hash.values ) else connection.execute <<-SQL DELETE FROM #{table} SQL end true end |
#update(ids, updates) ⇒ Object
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
# File 'lib/bloc_record/persistence.rb', line 26 def update(ids, updates) updates = BlocRecord::Utility.convert_keys(updates) updates.delete "id" updates_array = updates.keys.map { |key| "#{key} = ?" } if ids.class == Fixnum where_clause = "WHERE id = #{ids};" elsif ids.class == Array where_clause = ids.empty? ? ";" : "WHERE id IN (#{ids.join(",")});" else where_clause = ";" end connection.execute( "UPDATE #{table} SET #{updates_array.join(", ")} #{where_clause}", updates.values ) true end |
#update_all(updates) ⇒ Object
46 47 48 |
# File 'lib/bloc_record/persistence.rb', line 46 def update_all(updates) update(nil, updates) end |