Class: JsRequire

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

Defined Under Namespace

Classes: FileNotFoundInLoadpath

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(loadpaths = nil) ⇒ JsRequire

Returns a new instance of JsRequire.



9
10
11
12
13
14
15
16
# File 'lib/jsrequire.rb', line 9

def initialize(loadpaths = nil)
  @extract_loadpaths = []

  loadpaths = [loadpaths] unless loadpaths.is_a?(Array)
  @additional_loadpaths = JsRequire::normalize_filepaths(loadpaths.compact)

  @preprocessors = Hash.new { |h,k| h[k] = [] }
end

Class Method Details

.namespace_helper(files, namespace_prefix) ⇒ Object

builds namespaces from script files by pathnames when the <namespace_prefix> is found in path.

e.g.

namespace_helper([“/foo/bar/quux/file1.js”, “/foo/bar/baz/file2.js”], “bar”)

=> ["bar.baz", "bar.quux"]

Interessting for ExtJs#namespace



88
89
90
91
92
93
94
95
96
# File 'lib/jsrequire.rb', line 88

def self.namespace_helper(files, namespace_prefix)
  files.inject([]) do |arr,js|
    if js =~ /\/(#{namespace_prefix}\/.+)$/
      file = File.dirname($1).gsub("/", ".")
      arr << file
    end
    arr
  end.sort.uniq
end

.web_path_helper(files, webroots) ⇒ Object

convert absolute filepaths to relatives by cutting the absolute path to the webroot

returns the webroot relative filepaths

web_path_helper([“/foo/bar.js”], => “/javascripts”)

=> ["/javascripts/bar.js"]

Parameters:

  • webroots:

    array of strings to remove the prefix path or a hash to replace with defined string



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

def self.web_path_helper(files, webroots)
  webroots = [webroots] unless webroots.is_a?(Enumerable)

  files.map do |f|
    rel_file = nil
    webroots.each do |wr, replacement|
      wr = normalize_filepath(wr)
      rel_file = f.sub(/^#{Regexp.escape wr}/, replacement || '')
      break if rel_file != f
    end
    rel_file || f
  end
end

Instance Method Details

#on(action = nil, &block) ⇒ Object



19
20
21
# File 'lib/jsrequire.rb', line 19

def on(action = nil, &block)
  @preprocessors[action] << block
end

#resolve_dependencies(files) ⇒ Object

resolve dependencies of js input files

returns a hash with js and css dependencies

js files are returned with absolute filepaths, css files not. css files are returned as given by the parsed require statement.

e.g.

:javascripts => ["/foo/bar.js"],
:stylesheets => ["style.css"]



39
40
41
42
43
44
45
46
47
48
49
# File 'lib/jsrequire.rb', line 39

def resolve_dependencies(files)
  @stylesheets = Hash.new { |h,k| h[k] = [] }
  @extract_loadpaths = extract_loadpaths(files)

  js = extract_dependencies_recursive(JsRequire::normalize_filepaths(files))

  {
    :javascripts => js,
    :stylesheets => @stylesheets.map { |k,v| v }.flatten.uniq.sort
  }
end