Module: SelectableAttr::Base

Defined in:
lib/selectable_attr/base.rb

Defined Under Namespace

Modules: ClassMethods

Constant Summary collapse

ENUM_ARRAY_METHODS =
{
  :none => {
    :to_hash_array => Proc.new do |enum, attr_value|
      value = (attr_value || []).map(&:to_s)
      enum.to_hash_array do |hash|
        hash[:select] = value.include?(hash[:id].to_s)
      end
    end,

    :to_attr_value => Proc.new do |enum, hash_array|
      hash_array.select{|hash| hash[:select]}.map{|hash| hash[:id]}
    end
  },

  :comma_string => {
    :to_hash_array => Proc.new do |enum, attr_value|
      values = attr_value.is_a?(Array) ? attr_value.map{|v|v.to_s} :
        (attr_value || '').split(',')
      enum.to_hash_array do |hash|
        hash[:select] = values.include?(hash[:id].to_s)
      end
    end,

    :to_attr_value => Proc.new do |enum, hash_array|
      hash_array.select{|hash| hash[:select]}.map{|hash| hash[:id]}.join(',')
    end
  },


  :binary_string => {
    :to_hash_array => Proc.new do |enum, attr_value|
      value = attr_value || ''
      idx = 0
      enum.to_hash_array do |hash|
        hash[:select] = (value[idx, 1] == '1')
        idx += 1
      end
    end,

    :to_attr_value => Proc.new do |enum, hash_array|
      result = ''
      hash_map = hash_array.inject({}){|dest, hash| dest[hash[:id]] = hash; dest}
      enum.each do |entry|
        hash = hash_map[entry.id]
        result << (hash[:select] ? '1' : '0')
      end
      result
    end
  }
}

Class Method Summary collapse

Class Method Details

.included(base) ⇒ Object



4
5
6
# File 'lib/selectable_attr/base.rb', line 4

def self.included(base)
  base.extend(ClassMethods)
end