Module: ChattyError::ClassMethods

Defined in:
lib/chatty_error.rb

Instance Method Summary collapse

Instance Method Details

#caused_by(*args) ⇒ Object



58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/chatty_error.rb', line 58

def caused_by(*args)
  args.each do |method_name|
    class_name = self.name
    define_singleton_method method_name do |options={}|
      message = self.error_message(class_name, method_name, options)
      e = self.new(message)
      e.cause = method_name
      e.options = options
      return e
    end
  end
end

#configurationObject



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

def configuration
  if @configuration.nil? && self.superclass.methods.include?(:configuration)
    @configuration = self.superclass.configuration.clone
  else
    @configuration ||= Configuration.new
  end
end

#configuration=(conf) ⇒ Object



31
32
33
# File 'lib/chatty_error.rb', line 31

def configuration=(conf)
  @configuration = conf
end

#configure {|configuration| ... } ⇒ Object

Yields:



35
36
37
# File 'lib/chatty_error.rb', line 35

def configure
  yield configuration if block_given?
end

#error_message(name, method_name, options = {}) ⇒ Object



50
51
52
53
54
55
56
# File 'lib/chatty_error.rb', line 50

def error_message(name, method_name, options={})
  key = generate_key(name, method_name)
  I18n.t(key,
         :scope => configuration.default_scope,
         :default => [:default, configuration.default_message],
         :locale => options[:locale])
end

#generate_key(class_name, method_name) ⇒ Object



46
47
48
# File 'lib/chatty_error.rb', line 46

def generate_key(class_name, method_name)
  [underscore(class_name), method_name.to_s.downcase].join('.')
end

#underscore(string) ⇒ Object



39
40
41
42
43
44
# File 'lib/chatty_error.rb', line 39

def underscore(string)
  string.gsub(/::/, '.') \
    .gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2') \
    .gsub(/([a-z\d])([A-Z])/,'\1_\2') \
    .tr("-", "_").downcase
end