module RailsStuff::TransformAttrs

Generates writers which apply given transfromer for values.

Public Class Methods

fetch_block(ids) click to toggle source
# 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) click to toggle source

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
# File lib/rails_stuff/transform_attrs.rb, line 19
def register(name, &block)
  transformations[name] = block
end
transformations() click to toggle source
# File lib/rails_stuff/transform_attrs.rb, line 5
def transformations
  @transformations ||= {}
end

Public Instance Methods

transform_attrs(*attrs, with: nil, new_module: false, &block) click to toggle source

Options:

Calls superclass method
# 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_methods() click to toggle source

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

# File lib/rails_stuff/transform_attrs.rb, line 62
def transform_attrs_methods
  @transform_attrs_methods ||= Module.new.tap { |x| prepend x }
end