Class: ImportJS::Configuration

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

Overview

Class that initializes configuration from a .importjs.json file

Instance Method Summary collapse

Constructor Details

#initialize(path_to_current_file) ⇒ Configuration

Returns a new instance of Configuration.



26
27
28
29
30
31
32
33
34
# File 'lib/import_js/configuration.rb', line 26

def initialize(path_to_current_file)
  @path_to_current_file = normalize_path(path_to_current_file)
  @configs = []
  user_config = load_config(CONFIG_FILE)
  @configs.concat([user_config].flatten.reverse) if user_config
  @configs << DEFAULT_CONFIG

  check_current_version!
end

Instance Method Details

#get(key, from_file: nil) ⇒ Object

Returns a configuration value.

Returns:

  • (Object)

    a configuration value



37
38
39
40
41
42
43
44
45
# File 'lib/import_js/configuration.rb', line 37

def get(key, from_file: nil)
  @configs.find do |config|
    applies_to = config['applies_to'] || '*'
    applies_from = config['applies_from'] || '*'
    next unless config.key?(key)
    File.fnmatch(normalize_path(applies_to), @path_to_current_file) &&
      File.fnmatch(normalize_path(applies_from), normalize_path(from_file))
  end[key]
end

#package_dependenciesArray<String>

Returns:

  • (Array<String>)


77
78
79
80
81
82
83
84
85
86
# File 'lib/import_js/configuration.rb', line 77

def package_dependencies
  return [] unless File.exist?('package.json')

  keys = %w[dependencies peerDependencies]
  keys << 'devDependencies' if get('import_dev_dependencies')
  package_json = JSON.parse(File.read('package.json'))
  keys.map do |key|
    package_json[key].keys if package_json[key]
  end.compact.flatten
end

#resolve_alias(variable_name, path_to_current_file) ⇒ ImportJS::JSModule?

Parameters:

  • variable_name (String)
  • path_to_current_file (String?)

Returns:



50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/import_js/configuration.rb', line 50

def resolve_alias(variable_name, path_to_current_file)
  path = get('aliases')[variable_name]
  return unless path

  path = path['path'] if path.is_a? Hash

  if path_to_current_file && !path_to_current_file.empty?
    path = path.sub(/\{filename\}/,
                    File.basename(path_to_current_file, '.*'))
  end
  JSModule.new(import_path: path)
end

#resolve_named_exports(variable_name) ⇒ ImportJS::JSModule?

Parameters:

  • variable_name (String)

Returns:



65
66
67
68
69
70
71
72
73
74
# File 'lib/import_js/configuration.rb', line 65

def resolve_named_exports(variable_name)
  get('named_exports').each do |import_path, named_exports|
    next unless named_exports.include?(variable_name)

    js_module = JSModule.new(import_path: import_path)
    js_module.has_named_exports = true
    return js_module
  end
  nil
end