Module: RailsStuff::TransformAttrs

Defined in:
lib/rails_stuff/transform_attrs.rb

Overview

Generates writers which apply given transfromer for values.

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.fetch_block(ids) ⇒ Object



23
24
25
26
27
28
29
30
# File 'lib/rails_stuff/transform_attrs.rb', line 23

def fetch_block(ids)
  if ids.is_a?(Array)
    blocks = ids.map { |x| transformations.fetch(x) }
    ->(val) { blocks.reduce(val) { |x, block| block.call(x) } }
  else
    transformations.fetch(ids)
  end
end

.register(name, &block) ⇒ Object

Register new transformation with given block.

number_regexp = /\A\d+\z/
RailsStuff::TransformAttrs.register :phone do |val|
  if val && val.to_s =~ number_regexp
    ActiveSupport::NumberHelper.number_to_phone(val)
  else
    val
  end
end


19
20
21
# File 'lib/rails_stuff/transform_attrs.rb', line 19

def register(name, &block)
  transformations[name] = block
end

.transformationsObject



5
6
7
# File 'lib/rails_stuff/transform_attrs.rb', line 5

def transformations
  @transformations ||= {}
end

Instance Method Details

#transform_attrs(*attrs, with: nil, new_module: false, &block) ⇒ Object

Options:

  • ‘with` - use built-in transfromers from TransformAttrs.transformations. Add new transformations with TransformAttrs.register.

  • ‘new_module` - create new module for generated methods. Accepts `:prepend` or `:include`. By default it uses single module which is prepended.

    transform_attrs(:attr1, :attr2) { |x| x.to_s.downcase } transform_attrs(:attr3, &:presence) # to nullify blanks transform_attrs(:attr4, with: :strip) transform_attrs(:attr4, with: [:strip, :nullify]) transform_attrs(:attr5, new_module: :include)



50
51
52
53
54
55
56
57
58
59
# File 'lib/rails_stuff/transform_attrs.rb', line 50

def transform_attrs(*attrs, with: nil, new_module: false, &block)
  block ||= TransformAttrs.fetch_block(with)
  mod = Module.new.tap { |x| public_send(new_module, x) } if new_module
  mod ||= transform_attrs_methods
  mod.class_eval do
    attrs.each do |attr|
      define_method("#{attr}=") { |val| super(block[val]) }
    end
  end
end

#transform_attrs_methodsObject

Module to store generated methods, so they can be overriden in model.



62
63
64
# File 'lib/rails_stuff/transform_attrs.rb', line 62

def transform_attrs_methods
  @transform_attrs_methods ||= Module.new.tap { |x| prepend x }
end