class FastAttributes::TypeCast

Public Class Methods

escape_template(template, attribute_name, argument_name) click to toggle source
# File lib/fast_attributes/type_cast.rb, line 18
def escape_template(template, attribute_name, argument_name)
  template.gsub(/%+a|%+s/) do |match|
    match.each_char.each_slice(2).map do |placeholder|
      case placeholder
        when %w[% a] then attribute_name
        when %w[% s] then argument_name
        when %w[% %] then '%'
        else placeholder.join
      end
    end.join
  end
end
new(type) click to toggle source
# File lib/fast_attributes/type_cast.rb, line 9
def initialize(type)
  @type              = type
  @if_conditions     = []
  @else_condition    = %q(raise FastAttributes::TypeCast::UnknownTypeCastingError, 'Type casting is not defined')
  @rescue_conditions = nil
  @default_rescue    = %(raise FastAttributes::TypeCast::InvalidValueError, %(Invalid value "\#{%s}" for attribute "%a" of type "#{@type}"))
end

Public Instance Methods

compile_method_body(attribute_name, argument_name) click to toggle source
# File lib/fast_attributes/type_cast.rb, line 72
def compile_method_body(attribute_name, argument_name)
  method_body = "begin\n" +
                "  #{type_casting_template}\n" +
                "#{rescue_template}\n" +
                "end"

  self.class.escape_template(method_body, attribute_name, argument_name)
end
from(condition, options = {}) click to toggle source
# File lib/fast_attributes/type_cast.rb, line 32
def from(condition, options = {})
  @if_conditions << [condition, options[:to]]
end
on_error(error, options = {}) click to toggle source
# File lib/fast_attributes/type_cast.rb, line 40
def on_error(error, options = {})
  @rescue_conditions ||=[]
  @rescue_conditions << [error, options[:act]]
end
otherwise(else_condition) click to toggle source
# File lib/fast_attributes/type_cast.rb, line 36
def otherwise(else_condition)
  @else_condition = else_condition
end
rescue_template() click to toggle source
# File lib/fast_attributes/type_cast.rb, line 64
def rescue_template
  rescues = @rescue_conditions || [['', @default_rescue]]
  rescues.map do |error, action|
    "rescue #{error} => e\n" +
    "  #{action}"
  end.join("\n")
end
type_casting_template() click to toggle source
# File lib/fast_attributes/type_cast.rb, line 45
def type_casting_template
  @type_casting_template ||= begin
    if @if_conditions.any?
      conditions = @if_conditions.map do |from, to|
        "when #{from}\n" +
        "  #{to}\n"
      end

      "case %s\n" +
      conditions.join +
      "else\n" +
      "  #{@else_condition}\n" +
      "end"
    else
      @else_condition
    end
  end
end