Skip to content

Instantly share code, notes, and snippets.

@t0ster
Created January 23, 2011 22:02
Show Gist options
  • Save t0ster/792488 to your computer and use it in GitHub Desktop.
Save t0ster/792488 to your computer and use it in GitHub Desktop.
Python like import in coffee-script
Ti.API.debug "In tango.init"
IMPORTED = []
# Setting sys.path
sys = {}
sys.path = ['site-packages', '.']
class ImportError extends Error
constructor: (@message, @fileName, @lineNumber) ->
@name = 'ImportError'
#
# Python like import function
# Usage::
#
# imp 'tango.forms'
# # If `tango/forms` is a dir will include `tango/init.js`,
# # then `tango/forms/init.js`,
#
# # if it is `tango/forms.js` will include `tango/init.js`
# # then `tango/forms.js`.
#
# # If there are `tango/forms/init.js` and `tango/forms.js` present
# # will throw ImportError
#
# imp 'apps.students.models'
#
imp = (name, throw_exc=true) ->
Ti.API.debug "In tango.init.imp"
Ti.API.debug "name: #{ name }"
Ti.API.debug "throw_exc: #{ throw_exc }"
path_prefix = name.replace('.', '/', 'g')
Ti.API.debug "path_prefix: #{ path_prefix }"
get_path = (path_sufix) ->
Ti.API.debug "In tango.init.imp.get_path"
path = false
for _path in sys.path
Ti.API.debug "_path: #{ _path }"
Ti.API.debug "path_sufix: #{ path_sufix }"
file = Ti.Filesystem.getFile(_path, path_sufix)
Ti.API.debug "file: #{ file }"
Ti.API.debug "file.exist(): #{ file.exists() }"
if file.exists()
if path
throw new ImportError "Module duplication #{ name }"
path = file.nativePath
Ti.API.debug "path: #{ path }"
return path
path = get_path(path_prefix + '.js')
if /init$/.test(name)
if path
do_exports name
Ti.include path
Ti.API.debug "Included path: #{ path }"
return path
else
if throw_exc
throw new ImportError "No module named #{ name }"
else
return false
package_init_path = imp(name + '.init', false)
# This is package and we have included it's init, so just return
if package_init_path
return package_init_path
if not path
if throw_exc
throw new ImportError "No module named #{ name }"
else
return false
# Loading modules's init.js if this is module not package
if not package_init_path
init_file = Ti.Filesystem.getFile(Ti.Filesystem.getFile(path).getParent(), 'init.js')
if init_file.exists
do_exports name
Ti.include init_file.nativePath
do_exports name
Ti.include path
Ti.API.debug "Included path: #{ path }"
return path
# TODO(t0ster): memoize, do not import twice
do_exports = (name) ->
splits = name.split('.')
top_level = this
for module in splits
if not top_level[module]?
top_level[module] = {}
top_level = top_level[module]
# Global exports
@imp = imp
@sys = sys
@tango = {}
@tango.ImportError = ImportError
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment