diff --git a/lib/bitmask_attributes/value_proxy.rb b/lib/bitmask_attributes/value_proxy.rb index ea7d691..4c1fe80 100644 --- a/lib/bitmask_attributes/value_proxy.rb +++ b/lib/bitmask_attributes/value_proxy.rb @@ -1,6 +1,6 @@ module BitmaskAttributes class ValueProxy < Array - + def initialize(record, attribute, &extension) @record = record @attribute = attribute @@ -8,11 +8,11 @@ def initialize(record, attribute, &extension) instance_eval(&extension) if extension super(extract_values) end - + # ========================= # = OVERRIDE TO SERIALIZE = # ========================= - + alias_method :orig_replace, :replace %w(push << delete replace reject! select!).each do |override| class_eval(<<-EOEVAL) @@ -23,13 +23,17 @@ def #{override}(*args) end EOEVAL end - + def to_i inject(0) { |memo, value| memo | @mapping[value] } end - + + def to_s + join(', ') + end + private - + def validate! each do |value| if @mapping.key? value @@ -39,7 +43,7 @@ def validate! end end end - + def symbolize! orig_replace(map(&:to_sym)) end @@ -50,25 +54,25 @@ def updated! uniq! serialize! end - + def serialize! @record.send(:write_attribute, @attribute, to_i) end - + def extract_values stored = [@record.send(:read_attribute, @attribute) || 0, 0].max @mapping.inject([]) do |values, (value, bitmask)| values.tap do values << value.to_sym if (stored & bitmask > 0) end - end + end end - + def find_mapping unless (@mapping = @record.class.bitmasks[@attribute]) raise ArgumentError, "Could not find mapping for bitmask attribute :#{@attribute}" end end - + end end diff --git a/test/bitmask_attributes_test.rb b/test/bitmask_attributes_test.rb index 3caef99..a265b5a 100644 --- a/test/bitmask_attributes_test.rb +++ b/test/bitmask_attributes_test.rb @@ -282,6 +282,16 @@ def self.context_with_classes(label,campaign_class,company_class) assert_equal [], @campaign_class.with_exact_allow_zero(:none, :one) end + should 'return friendly value with to_s only' do + singular = @campaign_class.new(:medium => :web).medium + plural = @campaign_class.new(:medium => [:web, :print]).medium + + assert_equal singular, [:web] + assert_equal plural, [:web, :print] + assert_equal singular.to_s, 'web' + assert_equal plural.to_s, 'web, print' + end + private