Module: Normalizy::Extension::ClassMethods

Defined in:
lib/normalizy/extensions.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#normalizy_rulesObject

Returns the value of attribute normalizy_rules.



74
75
76
# File 'lib/normalizy/extensions.rb', line 74

def normalizy_rules
  @normalizy_rules
end

Instance Method Details

#normalizy(*args, &block) ⇒ Object



76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
# File 'lib/normalizy/extensions.rb', line 76

def normalizy(*args, &block)
  options = args.extract_options!
  rules   = options[:with]

  self.normalizy_rules ||= {}

  args.each do |field|
    normalizy_rules[field] ||= []
    normalizy_rules[field] << { block: block, options: options.except(:with), rules: rules }
  end

  prepend Module.new {
    args.each do |attribute|
      define_method :"#{attribute}=" do |value|
        result = normalizy!(
          attribute: attribute,
          block:     block,
          options:   options.except(:with),
          rules:     rules,
          value:     value
        )

        if rules.is_a?(Hash) && rules.dig(:slug, :to).present?
          write_attribute rules.dig(:slug, :to), result

          super value
        else
          super result
        end
      end
    end
  }
end