Sha256: 6bf90ae88f271db30e411a3138a1c20fc3b6388a28f12d9d3c254eeeeeb85806

Contents?: true

Size: 1.25 KB

Versions: 6

Compression:

Stored size: 1.25 KB

Contents

module Redirector
  module RegexAttribute

    def regex_attribute(attribute_name)
      include ValidationMethod

      cattr_accessor :regex_attribute_name
      self.regex_attribute_name = attribute_name

      validate :regex_attribute_is_valid_regex
      # Not working with rails 5.0.1
      if Rails.version.to_i < 5
        validates "#{attribute_name}_is_regex".to_sym, :inclusion => { :in => ['0', '1', true, false] }
        validates "#{attribute_name}_is_case_sensitive".to_sym, :inclusion => { :in => ['0', '1', true, false] }
      end

      define_method("#{regex_attribute_name}_regex") do
        if self.send("#{regex_attribute_name}_is_case_sensitive?")
          Regexp.compile(self.send(regex_attribute_name))
        else
          Regexp.compile(self.send(regex_attribute_name), Regexp::IGNORECASE)
        end
      end
    end

    module ValidationMethod

      protected

      def regex_attribute_is_valid_regex
        if self.send("#{regex_attribute_name}_is_regex?") && self.send("#{regex_attribute_name}?")
          begin
            Regexp.compile(self.send(regex_attribute_name))
          rescue RegexpError
            errors.add(regex_attribute_name, 'is an invalid regular expression')
          end
        end
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
redirector-1.1.7 lib/redirector/regex_attribute.rb
redirector-1.1.6 lib/redirector/regex_attribute.rb
redirector-1.1.5 lib/redirector/regex_attribute.rb
redirector-1.1.4 lib/redirector/regex_attribute.rb
redirector-1.1.3 lib/redirector/regex_attribute.rb
redirector-1.1.2 lib/redirector/regex_attribute.rb