Skip to content
This repository was archived by the owner on Jun 28, 2023. It is now read-only.

Commit 927b051

Browse files
committed
Merge pull request joelmoss#3 from pathable/friendly-strings
friendly name support via to_s
2 parents 2197d81 + 04ae935 commit 927b051

File tree

2 files changed

+26
-12
lines changed

2 files changed

+26
-12
lines changed

lib/bitmask_attributes/value_proxy.rb

Lines changed: 16 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,18 @@
11
module BitmaskAttributes
22
class ValueProxy < Array
3-
3+
44
def initialize(record, attribute, &extension)
55
@record = record
66
@attribute = attribute
77
find_mapping
88
instance_eval(&extension) if extension
99
super(extract_values)
1010
end
11-
11+
1212
# =========================
1313
# = OVERRIDE TO SERIALIZE =
1414
# =========================
15-
15+
1616
alias_method :orig_replace, :replace
1717
%w(push << delete replace reject! select!).each do |override|
1818
class_eval(<<-EOEVAL)
@@ -23,13 +23,17 @@ def #{override}(*args)
2323
end
2424
EOEVAL
2525
end
26-
26+
2727
def to_i
2828
inject(0) { |memo, value| memo | @mapping[value] }
2929
end
30-
30+
31+
def to_s
32+
join(', ')
33+
end
34+
3135
private
32-
36+
3337
def validate!
3438
each do |value|
3539
if @mapping.key? value
@@ -39,7 +43,7 @@ def validate!
3943
end
4044
end
4145
end
42-
46+
4347
def symbolize!
4448
orig_replace(map(&:to_sym))
4549
end
@@ -50,25 +54,25 @@ def updated!
5054
uniq!
5155
serialize!
5256
end
53-
57+
5458
def serialize!
5559
@record.send(:write_attribute, @attribute, to_i)
5660
end
57-
61+
5862
def extract_values
5963
stored = [@record.send(:read_attribute, @attribute) || 0, 0].max
6064
@mapping.inject([]) do |values, (value, bitmask)|
6165
values.tap do
6266
values << value.to_sym if (stored & bitmask > 0)
6367
end
64-
end
68+
end
6569
end
66-
70+
6771
def find_mapping
6872
unless (@mapping = @record.class.bitmasks[@attribute])
6973
raise ArgumentError, "Could not find mapping for bitmask attribute :#{@attribute}"
7074
end
7175
end
72-
76+
7377
end
7478
end

test/bitmask_attributes_test.rb

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -282,6 +282,16 @@ def self.context_with_classes(label,campaign_class,company_class)
282282
assert_equal [], @campaign_class.with_exact_allow_zero(:none, :one)
283283
end
284284

285+
should 'return friendly value with to_s only' do
286+
singular = @campaign_class.new(:medium => :web).medium
287+
plural = @campaign_class.new(:medium => [:web, :print]).medium
288+
289+
assert_equal singular, [:web]
290+
assert_equal plural, [:web, :print]
291+
assert_equal singular.to_s, 'web'
292+
assert_equal plural.to_s, 'web, print'
293+
end
294+
285295

286296
private
287297

0 commit comments

Comments
 (0)