Module: Intercom::Utils

Defined in:
lib/intercom/utils.rb

Class Method Summary collapse

Class Method Details

.constantize(camel_cased_word) ⇒ Object

the constantize method that exists in rails to allow for ruby 1.9 to get namespaced constants



14
15
16
17
18
19
20
21
22
23
# File 'lib/intercom/utils.rb', line 14

def constantize(camel_cased_word)
  names = camel_cased_word.split('::')
  names.shift if names.empty? || names.first.empty?

  constant = Object
  names.each do |name|
    constant = constant.const_defined?(name) ? constant.const_get(name) : constant.const_missing(name)
  end
  constant
end

.constantize_resource_name(resource_name) ⇒ Object



33
34
35
36
37
38
# File 'lib/intercom/utils.rb', line 33

def constantize_resource_name(resource_name)
  class_name = Utils.singularize(resource_name.capitalize)
  define_lightweight_class(class_name) unless Intercom.const_defined?(class_name, false)
  namespaced_class_name = "Intercom::#{class_name}"
  constantize namespaced_class_name
end

.constantize_singular_resource_name(resource_name) ⇒ Object



40
41
42
43
44
45
# File 'lib/intercom/utils.rb', line 40

def constantize_singular_resource_name(resource_name)
  class_name = resource_name.split('_').map(&:capitalize).join
  define_lightweight_class(class_name) unless Intercom.const_defined?(class_name, false)
  namespaced_class_name = "Intercom::#{class_name}"
  constantize namespaced_class_name
end

.define_lightweight_class(class_name) ⇒ Object



47
48
49
50
51
52
53
# File 'lib/intercom/utils.rb', line 47

def define_lightweight_class(class_name)
  #File.open('./intercom_ruby_dynamically_defined_classes.log', 'a') {|f| f.puts("Dynamically defining the class Intercom::#{class_name}") } #HACK
  new_class_definition = Class.new(Object) do
    include Traits::ApiResource
  end
  Intercom.const_set(class_name, new_class_definition)
end

.entity_key_from_type(type) ⇒ Object



55
56
57
58
59
# File 'lib/intercom/utils.rb', line 55

def entity_key_from_type(type)
  is_list = type.split('.')[1] == 'list'
  entity_name = type.split('.')[0]
  is_list ?  Utils.pluralize(entity_name) : entity_name
end

.pluralize(str) ⇒ Object



8
9
10
11
# File 'lib/intercom/utils.rb', line 8

def pluralize(str)
  return str.gsub(/y$/, 'ies') if str =~ /y$/
  "#{str}s"
end

.resource_class_to_collection_name(resource_class) ⇒ Object



29
30
31
# File 'lib/intercom/utils.rb', line 29

def resource_class_to_collection_name(resource_class)
  Utils.pluralize(resource_class_to_singular_name(resource_class))
end

.resource_class_to_singular_name(resource_class) ⇒ Object



25
26
27
# File 'lib/intercom/utils.rb', line 25

def resource_class_to_singular_name(resource_class)
  resource_class.to_s.split('::')[-1].downcase
end

.singularize(str) ⇒ Object



4
5
6
# File 'lib/intercom/utils.rb', line 4

def singularize(str)
  str.gsub(/ies$/, 'y').gsub(/s$/, '')
end