Skip to content

Commit e8dacd5

Browse files
committed
Merge pull request #164 from szTheory/master
For *_equals_any conditions, cast single values to an array, ex: 5 to [5] or 'ben' to ['ben']
2 parents 86ffca5 + 3839d3e commit e8dacd5

File tree

3 files changed

+24
-4
lines changed

3 files changed

+24
-4
lines changed

lib/searchlogic/search/method_missing.rb

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,12 +15,15 @@ def method_missing(name, *args, &block)
1515
if setter?(name)
1616
if scope?(scope_name)
1717
if args.size == 1
18+
options = scope_options(scope_name).respond_to?(:searchlogic_options) ? scope_options(scope_name).searchlogic_options : {}
19+
options[:cast_single_val_to_array] = cast_single_val_to_array?(condition_name)
20+
1821
write_condition(
1922
condition_name,
2023
type_cast(
2124
args.first,
2225
cast_type(scope_name),
23-
scope_options(scope_name).respond_to?(:searchlogic_options) ? scope_options(scope_name).searchlogic_options : {}
26+
options
2427
)
2528
)
2629
else
@@ -100,19 +103,24 @@ def type_cast(value, type, options = {})
100103
casted_value = column_for_type_cast.type_cast(value)
101104

102105
if Time.zone && casted_value.is_a?(Time)
103-
if value.is_a?(String)
106+
casted_value = if value.is_a?(String)
104107
# if its a string, we should assume the user means the local time
105108
# we need to update the object to include the proper time zone without changing
106109
# the time
107110
(casted_value + (Time.zone.utc_offset * -1)).in_time_zone(Time.zone)
108111
else
109112
casted_value.in_time_zone
110113
end
111-
else
112-
casted_value
113114
end
115+
116+
options[:cast_single_val_to_array] ? [casted_value] : casted_value
114117
end
115118
end
119+
120+
# For *_equals_any conditions, cast single values to an array, ex: 5 to [5] or 'ben' to ['ben']
121+
def cast_single_val_to_array?(condition_name)
122+
condition_name =~ /^\w+_equals_any/
123+
end
116124
end
117125
end
118126
end

searchlogic-2.5.13.gem

-102 KB
Binary file not shown.

spec/searchlogic/search_spec.rb

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -321,6 +321,18 @@
321321
search.id_equals_any.should == [1, 2, 3]
322322
end
323323

324+
it "should be an Array given a single value for *_equals_any" do
325+
search = Order.search
326+
search.id_equals_any = 5
327+
search.id_equals_any.should == [5]
328+
end
329+
330+
it "shouldn't change to an Array given a single value for *_equals" do
331+
search = Order.search
332+
search.id_equals = 5
333+
search.id_equals.should_not == [5]
334+
end
335+
324336
it "should type cast association conditions" do
325337
search = User.search
326338
search.orders_total_gt = "10"

0 commit comments

Comments
 (0)