class Typero::Type
Constants
- ERRORS
- OPTS
default shared allowed opts keys
- OPTS_KEYS
Attributes
opts[R]
Public Class Methods
allowed_opt?(name) { |msg| ... }
click to toggle source
# File lib/typero/type/type.rb, line 61 def allowed_opt? name return true if OPTS_KEYS.include?(name) OPTS[self] ||= {} return true if OPTS[self][name] msg = %[Unallowed param "#{name}" for type "#{to_s}" found. Allowed are "#{OPTS_KEYS.join(', ')}"] msg += %[ + "#{OPTS[self].keys.join(', ')}"] if OPTS[self].keys.first block_given? ? yield(msg) : raise(ArgumentError, msg) false end
error(locale, key, message)
click to toggle source
# File lib/typero/type/type.rb, line 50 def error locale, key, message locale = locale.to_sym ERRORS[locale] ||= {} ERRORS[locale][key.to_sym] = message end
load(name)
click to toggle source
# File lib/typero/type/type.rb, line 40 def load name klass = 'Typero::%sType' % name.to_s.gsub(/[^\w]/,'').classify if const_defined? klass klass.constantize else raise ArgumentError, 'Typero type "%s" is not defined (%s)' % [name, klass] end end
new(value, opts={})
click to toggle source
# File lib/typero/type/type.rb, line 78 def initialize value, opts={}, &block value = value.strip.rstrip if value.is_a?(String) opts.keys.each {|key| self.class.allowed_opt?(key) } @value = value @opts = opts @block = block end
opts(key, desc)
click to toggle source
# File lib/typero/type/type.rb, line 56 def opts key, desc OPTS[self] ||= {} OPTS[self][key] = desc end
Public Instance Methods
db_field()
click to toggle source
# File lib/typero/type/type.rb, line 110 def db_field out = db_schema out[1] ||= {} out[1][:default] ||= opts[:default] unless opts[:default].nil? out[1][:null] = false if !opts[:array] && opts[:required] out end
default()
click to toggle source
# File lib/typero/type/type.rb, line 106 def default nil end
get()
click to toggle source
# File lib/typero/type/type.rb, line 96 def get if value.nil? opts[:default].nil? ? default : opts[:default] else set error_for(:not_in_range, opts[:values].join(', ')) if opts[:values] && !opts[:values].include?(@value) value end end
value(&block)
click to toggle source
# File lib/typero/type/type.rb, line 88 def value &block if block_given? @value = block.call @value else @value end end
Private Instance Methods
error_for(name, *args)
click to toggle source
get error from option or the default one
# File lib/typero/type/type.rb, line 121 def error_for name, *args locale = if defined?(Lux) Lux.current.locale.to_s elsif defined?(I18n) I18n.locale end locale = :en if locale.to_s == '' pointer = ERRORS[locale.to_sym] || ERRORS[:en] error = @opts.dig(:meta, locale, name) || @opts.dig(:meta, name) || pointer[name] error = error % args if args.first raise 'Type error :%s not defined' % name unless error raise TypeError.new(error) end