Module: Cequel::Model::Magic
- Defined in:
- lib/cequel/model/magic.rb
Constant Summary
collapse
- FIND_BY_PATTERN =
/^find_by_(\w+)$/
- FIND_ALL_BY_PATTERN =
/^find_all_by_(\w+)$/
- FIND_OR_CREATE_BY_PATTERN =
/^find_or_create_by_(\w+)$/
- FIND_OR_INITIALIZE_BY_PATTERN =
/^find_or_initialize_by_(\w+)$/
Class Method Summary
collapse
Instance Method Summary
collapse
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(method, *args, &block) ⇒ Object
60
61
62
63
64
65
66
67
68
69
70
71
72
73
|
# File 'lib/cequel/model/magic.rb', line 60
def method_missing(method, *args, &block)
case method.to_s
when FIND_BY_PATTERN
Magic.scope(all, $1, args).first
when FIND_ALL_BY_PATTERN
Magic.scope(all, $1, args).to_a
when FIND_OR_CREATE_BY_PATTERN
Magic.find_or_create_by(all, $1, args, &block)
when FIND_OR_INITIALIZE_BY_PATTERN
Magic.find_or_initialize_by(all, $1, args, &block)
else
super
end
end
|
Class Method Details
36
37
38
39
40
41
42
43
44
45
46
47
|
# File 'lib/cequel/model/magic.rb', line 36
def self.(columns_string, args)
columns = columns_string.split('_and_').map { |column| column.to_sym }
if args.length == 1 && args.first.is_a?(Hash)
args.first.symbolize_keys.slice(*columns)
else
if columns.length != args.length
raise ArgumentError,
"wrong number of arguments(#{args.length} for #{columns.length})"
end
Hash[columns.zip(args)]
end
end
|
.find_or_create_by(scope, columns_string, args, &block) ⇒ Object
16
17
18
19
20
|
# File 'lib/cequel/model/magic.rb', line 16
def self.find_or_create_by(scope, columns_string, args, &block)
find_or_initialize_by(scope, columns_string, args, &block).tap do |instance|
instance.save unless instance.persisted?
end
end
|
.find_or_initialize_by(scope, columns_string, args, &block) ⇒ Object
22
23
24
25
26
27
28
29
30
31
32
33
34
|
# File 'lib/cequel/model/magic.rb', line 22
def self.find_or_initialize_by(scope, columns_string, args, &block)
row_specifications = (columns_string, args)
instance = scope.where(row_specifications).first
if instance.nil?
if args.length == 1 && args.first.is_a?(Hash)
attributes = args.first
else
attributes = row_specifications
end
instance = scope.new(attributes, &block)
end
instance
end
|
.scope(scope, columns_string, args) ⇒ Object
12
13
14
|
# File 'lib/cequel/model/magic.rb', line 12
def self.scope(scope, columns_string, args)
scope.where((columns_string, args))
end
|
Instance Method Details
#respond_to?(method, priv = false) ⇒ Boolean