Class: MiniMagick::Tool::OptionMethods

Inherits:
Module
  • Object
show all
Defined in:
lib/mini_magick/tool.rb

Overview

Dynamically generates modules with dynamically generated option methods for each command-line tool. It uses the ‘-help` page of a command-line tool and generates methods from it. It then includes the generated module into the tool class.

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(tool_name) ⇒ OptionMethods

Returns a new instance of OptionMethods.



201
202
203
204
205
# File 'lib/mini_magick/tool.rb', line 201

def initialize(tool_name)
  @tool_name = tool_name
  reload_methods
  self.class.instances << self
end

Class Method Details

.instancesObject

think about it for a minute



197
198
199
# File 'lib/mini_magick/tool.rb', line 197

def self.instances
  @instances ||= []
end

Instance Method Details

#cli_optionsObject



261
262
263
264
# File 'lib/mini_magick/tool.rb', line 261

def cli_options
  help = MiniMagick::Tool.new(@tool_name, false) { |b| b << "-help" }
  cli_options = help.scan(/^\s+-[a-z\-]+/).map(&:strip)
end

#creation_operator(*operators) ⇒ Object

Creates method based on creation operator’s name.

mogrify = MiniMagick::Tool.new("mogrify")
mogrify.canvas("khaki")
mogrify.command.join(" ") #=> "mogrify canvas:khaki"


247
248
249
250
251
252
253
254
# File 'lib/mini_magick/tool.rb', line 247

def creation_operator(*operators)
  operators.each do |operator|
    define_method(operator.gsub('-', '_')) do |value = nil|
      self << "#{operator}:#{value}"
      self
    end
  end
end

#creation_operatorsObject



256
257
258
259
# File 'lib/mini_magick/tool.rb', line 256

def creation_operators
  %w[xc canvas logo rose gradient radial-gradient
     plasma tile pattern label caption text]
end

#option(*options) ⇒ Object

Creates method based on command-line option’s name.

mogrify = MiniMagick::Tool.new("mogrify")
mogrify.antialias
mogrify.depth(8)
mogrify.resize("500x500")
mogirfy.command.join(" ")
#=> "mogrify -antialias -depth 8 -resize 500x500"


230
231
232
233
234
235
236
237
238
# File 'lib/mini_magick/tool.rb', line 230

def option(*options)
  options.each do |option|
    define_method(option[1..-1].gsub('-', '_')) do |*values|
      self << option
      self.merge!(values)
      self
    end
  end
end

#reload_methodsObject

Dynamically generates operator methods from the “-help” page.



214
215
216
217
218
# File 'lib/mini_magick/tool.rb', line 214

def reload_methods
  instance_methods(false).each { |method| undef_method(method) }
  creation_operator *creation_operators
  option *cli_options
end

#to_sObject



207
208
209
# File 'lib/mini_magick/tool.rb', line 207

def to_s
  "OptionMethods(#{@tool_name})"
end