lib/facemock/database/table.rb in facemock-0.0.6 vs lib/facemock/database/table.rb in facemock-0.0.7
- old
+ new
@@ -8,10 +8,11 @@
# 以下は継承先でオーバーライド必須
# * TABLE_NAME, COLUMN_NAMES
# * initialize()
TABLE_NAME = :tables
COLUMN_NAMES = [:id, :text, :active, :number, :created_at]
+ CHILDREN = []
def initialize(options={})
opts = Hashie::Mash.new(options)
self.id = opts.id
self.text = opts.text
@@ -25,19 +26,22 @@
end
def update_attributes!(options)
# カラムに含まれるかどうかの確認。なければNoMethodError
options.each_key {|key| self.send(key) }
- if persisted?
- update!(options)
- else
- insert!(options)
- end
+ persisted? ? update!(options) : insert!(options)
end
def destroy
raise unless persisted?
+ self.class.children.each do |klass|
+ klass_last_name = self.class.name.split("::").last.downcase
+ find_method_name = "find_all_by_#{klass_last_name}_id"
+ objects = klass.send(find_method_name, self.id)
+ objects.each{|object| object.destroy }
+ end
+
execute "DELETE FROM #{table_name} WHERE ID = #{self.id};"
self
end
def fetch
@@ -68,10 +72,16 @@
super
end
end
end
+ def self.create!(options={})
+ instance = self.new(options)
+ instance.save!
+ instance
+ end
+
def self.all
records = execute "SELECT * FROM #{table_name};"
records_to_objects(records)
end
@@ -93,19 +103,17 @@
records = execute "SELECT * FROM #{table_name} WHERE #{column_name} = #{column_value};"
records_to_objects(records)
end
def self.method_missing(name, *args)
- if name =~ /^find_by_(.+)/ || name =~ /^find_all_by_(.+)/
- column_name = $1
+ if ((name =~ /^find_by_(.+)/ || name =~ /^find_all_by_(.+)/) &&
+ (column_name = $1) && column_names.include?(column_name.to_sym))
+ raise ArgumentError, "wrong number of arguments (#{args.size} for 1)" unless args.size == 1
+ define_find_method(name, column_name) ? send(name, args.first) : super
else
super
end
- super unless column_names.include?(column_name.to_sym)
- raise ArgumentError, "wrong number of arguments (#{args.size} for 1)" unless args.size == 1
- super unless define_find_method(name, column_name)
- send(name, args.first)
end
def table_name
self.class.table_name
end
@@ -122,9 +130,13 @@
self::TABLE_NAME
end
def self.column_names
self::COLUMN_NAMES
+ end
+
+ def self.children
+ self::CHILDREN
end
def self.column_type(column_name)
return nil unless column_names.include?(column_name.to_s.to_sym)
table_info.send(column_name).type