Class: GrassGis::Module

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

Overview

Generate and execute GRASS commands

r = GrassGis::Module.new('r')
r.resamp.stats '-n', input: "map1@mapset1", output: "map2"

To execute a command without arguments, run must be invoked explicitly:

g = GrassGis::Module.new('g')
g.region.run

Instance Method Summary collapse

Constructor Details

#initialize(id, options = {}) ⇒ Module

Returns a new instance of Module.



14
15
16
17
18
19
20
# File 'lib/grassgis/module.rb', line 14

def initialize(id, options = {})
  @id = id.to_s
  @parent = options[:parent]
  @configuration = options[:configuration] || {}
  @history = @configuration[:history] || []
  @errors = @configuration[:errors] || :raise
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args) ⇒ Object



71
72
73
74
75
76
77
78
# File 'lib/grassgis/module.rb', line 71

def method_missing(method, *args)
  m = Module.new(method, parent: self, configuration: @configuration)
  if args.size > 0
    m.run *args
  else
    m
  end
end

Instance Method Details

#nameObject



22
23
24
25
26
27
28
# File 'lib/grassgis/module.rb', line 22

def name
  if @parent
    "#{@parent.name}.#{@id}"
  else
    @id
  end
end

#run(*args) ⇒ Object

Executes the command (with given arguments) returns a SysCmd object (with status, status_value, output, error_output methods)



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/grassgis/module.rb', line 32

def run(*args)
  stdin = nil
  cmd = SysCmd.command name do
    args.each do |arg|
      case arg
      when Hash
        arg.each do |key, value|
          case value
          when Array
            value = value*","
          when String
            if value.include?("\n")
              raise "Cannot pass multiple options through STDIN" if stdin
              stdin = Support.unindent(value)
              value = "-"
              input stdin
            end
          end
          option key.to_s, equal_value: value
        end
      else
        option arg
      end
    end
  end
  @history << cmd
  unless @configuration[:dry]
    run_options = {}
    if @errors == :console
      run_options[:error_output] = :console
    else
      run_options[:error_output] = :separate
    end
    cmd.run run_options
  end
  GrassGis.error cmd, @errors
  cmd
end