maksar-tmdb_party 0.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
data/.document ADDED
@@ -0,0 +1,5 @@
1
+ README.rdoc
2
+ lib/**/*.rb
3
+ bin/*
4
+ features/**/*.feature
5
+ LICENSE
data/.gitignore ADDED
@@ -0,0 +1,6 @@
1
+ *.sw?
2
+ .DS_Store
3
+ coverage
4
+ rdoc
5
+ pkg
6
+ apikey.txt
data/LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ Copyright (c) 2009 John Duff
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README.rdoc ADDED
@@ -0,0 +1,44 @@
1
+ = tmdb_party
2
+
3
+ Simple ruby wrapper to themoviedb.org (http://api.themoviedb.org/2.0/docs/) using HTTParty
4
+
5
+ = usage:
6
+ sudo gem install tmdb_party -s http://gemcutter.org
7
+ require 'rubygems'
8
+ require 'tmdb_party'
9
+
10
+ = example:
11
+
12
+ @tmdb = TMDBParty::Base.new('key')
13
+ results = @tmdb.search('transformers')
14
+
15
+ results.length
16
+ # => 5
17
+
18
+ transformers = results.detect{|m| m.name == "Transformers"}
19
+
20
+ transformers.popularity
21
+ # => 31
22
+ transformers.score
23
+ # => 1.0
24
+ transformers.imdb_id
25
+ # => 'tt0418279'
26
+
27
+ # some attributes don't come back with the search result, they are lazily loaded on demand
28
+ transformers.homepage
29
+ # => "http://www.transformersmovie.com/"
30
+ transformers.trailer.url
31
+ # => "http://www.youtube.com/watch?v=eduwcuq1Exg"
32
+
33
+ transformers.genres.collect{|cat| cat.name}.include?("Adventure")
34
+ # => true
35
+
36
+ = what is themoviedb.org?
37
+ It's a movie database, kind of like IMDB except it's more of a community wiki. They also have an api that they're cool with people using. More on the api here: http://api.themoviedb.org/2.0/docs/
38
+
39
+ == Contributors
40
+ Jon Maddox (http://github.com/maddox)
41
+
42
+ == Copyright
43
+
44
+ Copyright (c) 2009 John Duff. See LICENSE for details.
data/Rakefile ADDED
@@ -0,0 +1,60 @@
1
+ require 'rubygems'
2
+ require 'rake'
3
+
4
+ begin
5
+ require 'jeweler'
6
+ Jeweler::Tasks.new do |gem|
7
+ gem.name = "maksar-tmdb_party"
8
+ gem.summary = %Q{Simple ruby wrapper to themoviedb.org (http://api.themoviedb.org/2.0/docs/) using HTTParty}
9
+ gem.email = "Maksar.mail@gmail.com"
10
+ gem.homepage = "http://github.com/maksar/tmdb_party"
11
+ gem.authors = ["John Duff", "Jon Maddox", "Alexander Shestakov"]
12
+ gem.add_dependency('httparty', '>= 0.4.3')
13
+
14
+ gem.add_development_dependency('fakeweb')
15
+ gem.add_development_dependency('context')
16
+ # gem is a Gem::Specification... see http://www.rubygems.org/read/chapter/20 for additional settings
17
+ end
18
+ Jeweler::GemcutterTasks.new
19
+ rescue LoadError
20
+ puts "Jeweler (or a dependency) not available. Install it with: sudo gem install jeweler"
21
+ end
22
+
23
+ require 'rake/testtask'
24
+ Rake::TestTask.new(:test) do |test|
25
+ test.libs << 'lib' << 'test'
26
+ test.pattern = 'test/**/*_test.rb'
27
+ test.verbose = true
28
+ end
29
+
30
+ begin
31
+ require 'rcov/rcovtask'
32
+ Rcov::RcovTask.new do |test|
33
+ test.libs << 'test'
34
+ test.pattern = 'test/**/*_test.rb'
35
+ test.verbose = true
36
+ end
37
+ rescue LoadError
38
+ task :rcov do
39
+ abort "RCov is not available. In order to run rcov, you must: sudo gem install spicycode-rcov"
40
+ end
41
+ end
42
+
43
+
44
+ task :default => :test
45
+
46
+ require 'rake/rdoctask'
47
+ Rake::RDocTask.new do |rdoc|
48
+ if File.exist?('VERSION.yml')
49
+ config = YAML.load(File.read('VERSION.yml'))
50
+ version = "#{config[:major]}.#{config[:minor]}.#{config[:patch]}"
51
+ else
52
+ version = ""
53
+ end
54
+
55
+ rdoc.rdoc_dir = 'rdoc'
56
+ rdoc.title = "tmdb_party #{version}"
57
+ rdoc.rdoc_files.include('README*')
58
+ rdoc.rdoc_files.include('lib/**/*.rb')
59
+ end
60
+
data/VERSION.yml ADDED
@@ -0,0 +1,4 @@
1
+ ---
2
+ :patch: 2
3
+ :major: 0
4
+ :minor: 4
data/lib/tmdb_party.rb ADDED
@@ -0,0 +1,72 @@
1
+ # gem 'httparty'
2
+ require 'rubygems'
3
+ require 'httparty'
4
+
5
+ current_dir=File.expand_path(File.dirname(__FILE__))
6
+ unless $LOAD_PATH.first==(current_dir)
7
+ $LOAD_PATH.unshift(current_dir)
8
+ end
9
+
10
+ require "tmdb_party/core_extensions"
11
+ require "tmdb_party/httparty_icebox"
12
+ require "tmdb_party/attributes"
13
+ require "tmdb_party/video"
14
+ require "tmdb_party/genre"
15
+ require "tmdb_party/person"
16
+ require "tmdb_party/image"
17
+ require "tmdb_party/movie"
18
+
19
+ module TMDBParty
20
+ class Base
21
+ include HTTParty
22
+ include HTTParty::Icebox
23
+ cache :store => 'file', :timeout => 120, :location => Dir.tmpdir
24
+
25
+ base_uri 'http://api.themoviedb.org/2.1'
26
+ format :json
27
+
28
+ def readFile filename, maxlines=0
29
+ i=0
30
+ read_so_far=[]
31
+ f=File.open(File.expand_path(filename), 'r')
32
+ while (line=f.gets)
33
+ break if maxlines!=0 and i >= maxlines
34
+ read_so_far << line and i+=1
35
+ end
36
+ read_so_far
37
+ end
38
+
39
+ def initialize(key=nil)
40
+ !key.nil? ? (@api_key = key) : (@api_key= readFile('apikey.txt').first.strip)
41
+ end
42
+
43
+ def default_path_items
44
+ path_items = ['en']
45
+ path_items << 'json'
46
+ path_items << @api_key
47
+ end
48
+
49
+ def search(query)
50
+ data = self.class.get("/Movie.search/" + default_path_items.join('/') + '/' + URI.escape(query))
51
+ if data.class != Array || data.first == "Nothing found."
52
+ []
53
+ else
54
+ data.collect { |movie| Movie.new(movie, self) }
55
+ end
56
+ end
57
+
58
+ def imdb_lookup(imdb_id)
59
+ data = self.class.get("/Movie.imdbLookup/" + default_path_items.join('/') + '/' + imdb_id)
60
+ if data.class != Array || data.first == "Nothing found."
61
+ nil
62
+ else
63
+ Movie.new(data.first, self)
64
+ end
65
+ end
66
+
67
+ def get_info(id)
68
+ data = self.class.get("/Movie.getInfo/" + default_path_items.join('/') + '/' + id.to_s)
69
+ Movie.new(data.first, self)
70
+ end
71
+ end
72
+ end
@@ -0,0 +1,52 @@
1
+ module TMDBParty
2
+ module Attributes
3
+ # based on http://github.com/nullstyle/ruby-satisfaction
4
+
5
+ def self.included(base)
6
+ base.class_eval do
7
+ extend ClassMethods
8
+ include InstanceMethods
9
+ attr_reader :attributes
10
+ end
11
+ end
12
+
13
+ module ClassMethods
14
+ def attributes(*names)
15
+ options = names.extract_options!
16
+
17
+ names.each do |name|
18
+ attribute name, options unless name.blank?
19
+ end
20
+ end
21
+
22
+ def attribute(name, options)
23
+ options.replace({:type => 'nil', :lazy=>false}.merge(options))
24
+ raise "Name can't be empty" if name.blank?
25
+ lazy_load = "self.#{options[:lazy]} unless self.loaded?" if options[:lazy]
26
+ class_eval <<-EOS
27
+ def #{name}
28
+ #{lazy_load}
29
+ @#{name} ||= decode_raw_attribute(@attributes['#{name}'], #{options[:type]}) if @attributes
30
+ end
31
+ EOS
32
+ end
33
+
34
+ end
35
+
36
+ module InstanceMethods
37
+ def attributes=(value)
38
+ @attributes = value
39
+ end
40
+
41
+ def loaded?
42
+ @loaded
43
+ end
44
+
45
+ private
46
+ def decode_raw_attribute(value, type)
47
+ return nil unless value
48
+ type.respond_to?(:parse) ? type.parse(value) : value
49
+ end
50
+ end
51
+ end
52
+ end
@@ -0,0 +1,22 @@
1
+ module TMDBParty
2
+ class Category
3
+ include Attributes
4
+ attributes :name, :url
5
+
6
+ def initialize(values)
7
+ self.attributes = values
8
+ end
9
+
10
+ def self.parse(data)
11
+ return unless data
12
+ data = data["category"]
13
+ if data.is_a?(Array)
14
+ data.collect do |category|
15
+ Category.new(category)
16
+ end
17
+ else
18
+ [Category.new(data)]
19
+ end
20
+ end
21
+ end
22
+ end
@@ -0,0 +1,18 @@
1
+ class Array
2
+ def extract_options!
3
+ last.is_a?(::Hash) ? pop : {}
4
+ end
5
+
6
+ end
7
+
8
+ class Float
9
+ def self.parse(val)
10
+ Float(val)
11
+ end
12
+ end
13
+
14
+ class Integer
15
+ def self.parse(val)
16
+ Integer(val)
17
+ end
18
+ end
@@ -0,0 +1,21 @@
1
+ module TMDBParty
2
+ class Genre
3
+ include Attributes
4
+ attributes :name, :url
5
+
6
+ def initialize(values)
7
+ self.attributes = values
8
+ end
9
+
10
+ def self.parse(data)
11
+ return unless data
12
+ if data.is_a?(Array)
13
+ data.collect do |g|
14
+ Genre.new(g)
15
+ end
16
+ else
17
+ [Genre.new(data)]
18
+ end
19
+ end
20
+ end
21
+ end
@@ -0,0 +1,259 @@
1
+ # = Icebox : Caching for HTTParty
2
+ #
3
+ # Cache responses in HTTParty models [http://github.com/jnunemaker/httparty]
4
+ #
5
+ # === Usage
6
+ #
7
+ # class Foo
8
+ # include HTTParty
9
+ # include HTTParty::Icebox
10
+ # cache :store => 'file', :timeout => 600, :location => MY_APP_ROOT.join('tmp', 'cache')
11
+ # end
12
+ #
13
+ # Modeled after Martyn Loughran's APICache [http://github.com/newbamboo/api_cache]
14
+ # and Ruby On Rails's caching [http://api.rubyonrails.org/classes/ActiveSupport/Cache.html]
15
+ #
16
+ # Author: Karel Minarik [www.karmi.cz]
17
+ #
18
+ # === Notes
19
+ #
20
+ # Thanks to Amit Chakradeo to point out objects have to be stored marhalled on FS
21
+ # Thanks to Marlin Forbes to point out query parameters have to be include in the cache key
22
+ #
23
+ #
24
+
25
+ require 'logger'
26
+ require 'ftools'
27
+ require 'tmpdir'
28
+ require 'pathname'
29
+ require 'digest/md5'
30
+
31
+ module HTTParty #:nodoc:
32
+ module Icebox
33
+
34
+ module ClassMethods
35
+
36
+ # Enable caching and set cache options
37
+ # Returns memoized cache object
38
+ #
39
+ # Following options are available, default values are in []:
40
+ #
41
+ # +store+:: Storage mechanism for cached data (memory, filesystem, your own) [memory]
42
+ # +timeout+:: Cache expiration in seconds [60]
43
+ # +logger+:: Path to logfile or logger instance [STDOUT]
44
+ #
45
+ # Any additional options are passed to the Cache constructor
46
+ #
47
+ # Usage:
48
+ #
49
+ # # Enable caching in HTTParty, in memory, for 1 minute
50
+ # cache # Use default values
51
+ #
52
+ # # Enable caching in HTTParty, on filesystem (/tmp), for 10 minutes
53
+ # cache :store => 'file', :timeout => 600, :location => '/tmp/'
54
+ #
55
+ # # Use your own cache store (see AbstractStore class below)
56
+ # cache :store => 'memcached', :timeout => 600, :server => '192.168.1.1:1001'
57
+ #
58
+ def cache(options={})
59
+ options[:store] ||= 'memory'
60
+ options[:timeout] ||= 60
61
+ logger = options[:logger]
62
+ @cache ||= Cache.new( options.delete(:store), options )
63
+ end
64
+
65
+ end
66
+
67
+ # When included, extend class with +cache+ method
68
+ # and redefine +get+ method to use cache
69
+ #
70
+ def self.included(receiver) #:nodoc:
71
+ receiver.extend ClassMethods
72
+ receiver.class_eval do
73
+
74
+ # Get reponse from network
75
+ # TODO: Why alias :new :old is not working here? Returns NoMethodError
76
+ #
77
+ def self.get_without_caching(path, options={})
78
+ perform_request Net::HTTP::Get, path, options
79
+ end
80
+
81
+ # Get response from cache, if available
82
+ #
83
+ def self.get_with_caching(path, options={})
84
+ key = path.clone
85
+ key << options[:query].to_s if defined? options[:query]
86
+
87
+ if cache.exists?(key) and not cache.stale?(key)
88
+ Cache.logger.debug "CACHE -- GET #{path}#{options[:query]}"
89
+ return cache.get(key)
90
+ else
91
+ Cache.logger.debug "/!\\ NETWORK -- GET #{path}#{options[:query]}"
92
+ response = get_without_caching(path, options)
93
+ cache.set(key, response) if response.code == 200
94
+ return response
95
+ end
96
+ end
97
+
98
+ # Redefine original HTTParty +get+ method to use cache
99
+ #
100
+ def self.get(path, options={})
101
+ self.get_with_caching(path, options)
102
+ end
103
+
104
+ end
105
+ end
106
+
107
+ # === Cache container
108
+ #
109
+ # Pass a store name ('memory', etc) to initializer
110
+ #
111
+ class Cache
112
+ attr_accessor :store
113
+
114
+ def initialize(store, options={})
115
+ self.class.logger = options[:logger]
116
+ @store = self.class.lookup_store(store).new(options)
117
+ end
118
+
119
+ def get(key); @store.get encode(key) unless stale?(key); end
120
+ def set(key, value); @store.set encode(key), value; end
121
+ def exists?(key); @store.exists? encode(key); end
122
+ def stale?(key); @store.stale? encode(key); end
123
+
124
+ def self.logger; @logger || default_logger; end
125
+ def self.default_logger; logger = ::Logger.new(STDERR); end
126
+
127
+ # Pass a filename (String), IO object, Logger instance or +nil+ to silence the logger
128
+ def self.logger=(device); @logger = device.kind_of?(::Logger) ? device : ::Logger.new(device); end
129
+
130
+ private
131
+
132
+ # Return store class based on passed name
133
+ def self.lookup_store(name)
134
+ store_name = "#{name.capitalize}Store"
135
+ return Store::const_get(store_name)
136
+ rescue NameError => e
137
+ raise Store::StoreNotFound, "The cache store '#{store_name}' was not found. Did you loaded any such class?"
138
+ end
139
+
140
+ def encode(key); Digest::MD5.hexdigest(key); end
141
+ end
142
+
143
+
144
+ # === Cache stores
145
+ #
146
+ module Store
147
+
148
+ class StoreNotFound < StandardError; end #:nodoc:
149
+
150
+ # ==== Abstract Store
151
+ # Inherit your store from this class
152
+ # *IMPORTANT*: Do not forget to call +super+ in your +initialize+ method!
153
+ #
154
+ class AbstractStore
155
+ def initialize(options={})
156
+ raise ArgumentError, "You need to set the :timeout parameter" unless options[:timeout]
157
+ @timeout = options[:timeout]
158
+ message = "Cache: Using #{self.class.to_s.split('::').last}"
159
+ message << " in location: #{options[:location]}" if options[:location]
160
+ message << " with timeout #{options[:timeout]} sec"
161
+ Cache.logger.info message unless options[:logger].nil?
162
+ return self
163
+ end
164
+ %w{set get exists? stale?}.each do |method_name|
165
+ define_method(method_name) { raise NoMethodError, "Please implement method set in your store class" }
166
+ end
167
+ end
168
+
169
+ # ===== Store objects in memory
170
+ #
171
+ Struct.new("Response", :code, :body, :headers) { def to_s; self.body; end }
172
+ class MemoryStore < AbstractStore
173
+ def initialize(options={})
174
+ super; @store = {}; self
175
+ end
176
+ def set(key, value)
177
+ Cache.logger.info("Cache: set (#{key})")
178
+ @store[key] = [Time.now, value]; true
179
+ end
180
+ def get(key)
181
+ data = @store[key][1]
182
+ Cache.logger.info("Cache: #{data.nil? ? "miss" : "hit"} (#{key})")
183
+ data
184
+ end
185
+ def exists?(key)
186
+ !@store[key].nil?
187
+ end
188
+ def stale?(key)
189
+ return true unless exists?(key)
190
+ Time.now - created(key) > @timeout
191
+ end
192
+ private
193
+ def created(key)
194
+ @store[key][0]
195
+ end
196
+ end
197
+
198
+ # ===== Store objects on the filesystem
199
+ #
200
+ class FileStore < AbstractStore
201
+ def initialize(options={})
202
+ super
203
+ options[:location] ||= Dir::tmpdir
204
+ @path = Pathname.new( options[:location] )
205
+ FileUtils.mkdir_p( @path )
206
+ self
207
+ end
208
+ def set(key, value)
209
+ Cache.logger.info("Cache: set (#{key})")
210
+ File.open( @path.join(key), 'w' ) { |file| file << Marshal.dump(value) }
211
+ true
212
+ end
213
+ def get(key)
214
+ data = Marshal.load(File.read( @path.join(key)))
215
+ Cache.logger.info("Cache: #{data.nil? ? "miss" : "hit"} (#{key})")
216
+ data
217
+ end
218
+ def exists?(key)
219
+ File.exists?( @path.join(key) )
220
+ end
221
+ def stale?(key)
222
+ return true unless exists?(key)
223
+ Time.now - created(key) > @timeout
224
+ end
225
+ private
226
+ def created(key)
227
+ File.mtime( @path.join(key) )
228
+ end
229
+ end
230
+ end
231
+
232
+ end
233
+ end
234
+
235
+
236
+ # Major parts of this code are based on architecture of ApiCache.
237
+ # Copyright (c) 2008 Martyn Loughran
238
+ #
239
+ # Other parts are inspired by the ActiveSupport::Cache in Ruby On Rails.
240
+ # Copyright (c) 2005-2009 David Heinemeier Hansson
241
+ #
242
+ # Permission is hereby granted, free of charge, to any person obtaining
243
+ # a copy of this software and associated documentation files (the
244
+ # "Software"), to deal in the Software without restriction, including
245
+ # without limitation the rights to use, copy, modify, merge, publish,
246
+ # distribute, sublicense, and/or sell copies of the Software, and to
247
+ # permit persons to whom the Software is furnished to do so, subject to
248
+ # the following conditions:
249
+ #
250
+ # The above copyright notice and this permission notice shall be
251
+ # included in all copies or substantial portions of the Software.
252
+ #
253
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
254
+ # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
255
+ # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
256
+ # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
257
+ # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
258
+ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
259
+ # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.