Class: IMDB::Skeleton

Inherits:
Object
  • Object
show all
Defined in:
lib/imdb/skeleton.rb

Overview

IMDB generic interface.

Direct Known Subclasses

Movie, Person, Result

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(model_name = "", method_names = {}, keys = []) ⇒ Skeleton

Returns a new instance of Skeleton.



6
7
8
9
10
11
12
13
14
15
16
17
18
19
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
# File 'lib/imdb/skeleton.rb', line 6

def initialize(model_name = "", method_names = {}, keys = [])
  if IMDB::Configuration.caching
    @model = Class.new do
      include MongoMapper::Document
      set_collection_name model_name
      method_names.each { |m, t|
        key m, t
      }
    end
    class_eval do
      method_names.each_key { |meth|
        unless keys.include?(meth)
          old_meth = "old_#{meth}".to_sym
          alias_method old_meth, meth.to_sym
          define_method meth do
            k = keys.to_hash { |k| k; self.send(k) }

            @db_query = self.model.first(k)

            if @db_query.nil?
              @db_query = self.model.new(keys.to_hash { |k| k; self.send(k)})
              @db_query.save
            end

            if @db_query[meth].nil? or (@db_query[meth].length.zero? if @db_query[meth].kind_of?(Array))
              a = send(old_meth)
              if a.kind_of?(Array)
                a.compact!
                a.map! { |c|
                  if c.kind_of?(String)
                    c
                  else
                    c.to_hash
                  end
                }
                @db_query[meth] = a
              else
                @db_query[meth] = a
              end
              @db_query.save
            end
            @db_query[meth]
          end
        end
      }
    end
  end
  @method_names = method_names
end

Instance Attribute Details

#method_namesObject

Returns the value of attribute method_names.



4
5
6
# File 'lib/imdb/skeleton.rb', line 4

def method_names
  @method_names
end

#modelObject

Returns the value of attribute model.



4
5
6
# File 'lib/imdb/skeleton.rb', line 4

def model
  @model
end

Class Method Details

.json_create(o) ⇒ Object



78
79
80
# File 'lib/imdb/skeleton.rb', line 78

def self.json_create(o)
  new(*o['data'])
end

Instance Method Details

#to_hash(*a) ⇒ Object



63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/imdb/skeleton.rb', line 63

def to_hash(*a)
  tmp_hash = {}
  @method_names.each_key { |x|
    evaled = self.send x
    if evaled.kind_of?(Array)
      tmp_hash[x] = evaled.collect! {|e|
        e
      }
    elsif evaled.kind_of?(String)
      tmp_hash[x] = evaled
    end
  }
  tmp_hash
end

#to_json(*a) ⇒ Object

Serialize method’s output to json



57
58
59
60
61
# File 'lib/imdb/skeleton.rb', line 57

def to_json(*a)
  tmp_hash = to_hash

  tmp_hash.to_json(*a)
end