Sha256: 7d3e6e1cc100b525b8333a1e254f32936745e598c2209b4f15934c55a8e8b288

Contents?: true

Size: 1.49 KB

Versions: 1

Compression:

Stored size: 1.49 KB

Contents

module MaskableAttribute
  class MaskableAttribute
    attr_accessor :object, :attribute, :masks

    def initialize(object, attribute, masks, options)
      @object = object
      @attribute = attribute
      @masks = Masks.new masks
      @protected_prefixes = Array.wrap(options.delete(:protected_prefixes) || options.delete(:protected_prefix)).join('|')
    end

    def masks
      @masks.names
    end

    def masked
      value = unmasked
      if !value.blank? and value.match(/\{.*\}/)
        value.scan(/(?<={)[^}]+(?=})/).each do |mask| #mask: two_digit model_series
          mask_value = @masks[mask].unmask(@object)
          value = value.sub "{#{mask}}", mask_value.to_s unless mask_value.nil?
        end
      end
      value
    end

    alias :to_s :masked

    def masked_object
      @object
    end

    def unmasked
      @object.read_attribute attribute
    end

    def set(value)
      unless value.blank?
        @masks.each do |mask|
          mask.accessed_by.each do |mask_accessor|
            value.sub! /#{"(?<!#{@protected_prefixes})" unless @protected_prefixes.blank?}#{mask.unmask(@object, :formatted => mask_accessor)}(?![^{]*})/, "{#{mask_accessor}}" unless mask.unmask(@object).blank?
          end
        end
      end
      value
    end

    class InvalidMask < RuntimeError
      attr :mask, :obj
      def initialize(mask, obj)
        @mask = mask
        @obj = obj
      end

      def to_s
        "Invalid mask '#{@mask}' for #{@obj.class.name}"
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
maskable_attribute-0.0.5 lib/maskable_attribute/maskable_attribute.rb