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

Commit

Permalink
Merge pull request joelmoss#3 from pathable/friendly-strings
Browse files Browse the repository at this point in the history
friendly name support via to_s
  • Loading branch information
braddunbar committed Oct 23, 2012
2 parents 2197d81 + 04ae935 commit 927b051
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 12 deletions.
28 changes: 16 additions & 12 deletions lib/bitmask_attributes/value_proxy.rb
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
module BitmaskAttributes
class ValueProxy < Array

def initialize(record, attribute, &extension)
@record = record
@attribute = attribute
find_mapping
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)
Expand All @@ -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
Expand All @@ -39,7 +43,7 @@ def validate!
end
end
end

def symbolize!
orig_replace(map(&:to_sym))
end
Expand All @@ -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
10 changes: 10 additions & 0 deletions test/bitmask_attributes_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down

0 comments on commit 927b051

Please sign in to comment.