Module: Ordinary::ClassMethods

Defined in:
lib/ordinary.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#normalizersHash<Symbol, Array<Ordinary::Normalizer>> (readonly)

Returns normalizers for each attribute.

Returns:



97
98
99
# File 'lib/ordinary.rb', line 97

def normalizers
  @normalizers ||= {}
end

Instance Method Details

#normalizes(*attr_names) {|value| ... } ⇒ Object

Define normalization for attributes.

Examples:

define normalization with a builder for the normalizer


normalizes :name, lambda { lstrip }
normalizes :name, lambda { lstrip | rstrip }

define normalization with a block


normalizes :name do |value|
  value.squeeze(' ')
end

define normalization with a builder for the normalizer and a block


normalizes :name, -> { lstrip | block | rstrip } do |value|
  value.squeeze(' ')
end

Parameters:

  • attr_names (Array<Symbol>)

    attirubte names to normalize

Yields:

  • (value)

    normalize the attribute

Yield Parameters:

  • value (Object)

    value of the attribute to normalize



123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
# File 'lib/ordinary.rb', line 123

def normalizes(*attr_names, &block)
  attr_names = attr_names.dup
  buil       = nil
  options    = {}

  case attr_names.last
  when Proc
    build = attr_names.pop
  when Hash
    options = attr_names.pop.dup
    build = options.delete(:with)
  end

  unless build or block
    raise ArgumentError, 'process for building a normalizer'  \
                         '(with the last argument or :with option) or ' \
                         'an unit of a normalizer ' \
                         '(with block) are not given'
  end

  build ||= lambda { block }
  unit = Builder.new(&block).build(&build)
  normalizer = Normalizer.new(options, &unit)

  attr_names.each do |attr_name|
    raise ArgumentError, "##{attr_name} is not defined"  unless method_defined?(attr_name)
    raise ArgumentError, "##{attr_name}= is not defined" unless method_defined?(:"#{attr_name}=")

    (normalizers[attr_name.to_sym] ||= []) << normalizer

    define_method :"normalized_#{attr_name}" do |context = nil|
      normalize_attribute(attr_name, context)
    end
  end
end