Class: OData::ClassBuilder

Inherits:
Object
  • Object
show all
Defined in:
lib/ruby_odata/class_builder.rb

Overview

Internal helper class for building a dynamic class. This class shouldn't be called directly.

Instance Method Summary collapse

Constructor Details

#initialize(klass_name, methods, nav_props, context, namespace = nil) ⇒ ClassBuilder

Creates a new instance of the ClassBuilder class

Parameters:

  • klass_name (String)

    the name/type of the class to create

  • methods (Array)

    the accessor methods to add to the class

  • nav_props (Array)

    the accessor methods to add for navigation properties

  • context (Service)

    the service context that this entity belongs to

  • namespace (String, nil) (defaults to: nil)

    optional namespace to create the classes in



11
12
13
14
15
16
17
# File 'lib/ruby_odata/class_builder.rb', line 11

def initialize(klass_name, methods, nav_props, context, namespace = nil)
  @klass_name = klass_name.camelcase
  @methods = methods
  @nav_props = nav_props
  @context = context
  @namespace = namespace
end

Instance Method Details

#buildObject

Returns a dynamically generated class definition based on the constructor parameters



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/ruby_odata/class_builder.rb', line 20

def build
  # return if already built
  return @klass unless @klass.nil?

  # need the class name to build class
  return nil    if @klass_name.nil?

  # return if we can find constant corresponding to class name
  already_defined = eval("defined?(#{@klass_name}) == 'constant' and #{@klass_name}.class == Class")
  if already_defined
    @klass = @klass_name.constantize
    return @klass
  end

  if @namespace
    namespaces = @namespace.split(/\.|::/)

    namespaces.each_with_index do |ns, index|
      if index == 0
        next if Object.const_defined? ns
        Object.const_set(ns, Module.new)
      else
        current_ns = namespaces[0..index-1].join '::'
        next if eval "#{current_ns}.const_defined? '#{ns}'"
        eval "#{current_ns}.const_set('#{ns}', Module.new)"
      end
    end

    klass_constant = @klass_name.split('::').last
    eval "#{namespaces.join '::'}.const_set('#{klass_constant}', Class.new.extend(ActiveSupport::JSON))"
  else
    Object.const_set(@klass_name, Class.new.extend(ActiveSupport::JSON))
  end

  @klass = @klass_name.constantize
  @klass.class_eval do
    include OData
  end

  add_initializer(@klass)
  add_methods(@klass)
  add_nav_props(@klass)
  add_class_methods(@klass)

  return @klass
end