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.



189
190
191
192
193
# File 'lib/mini_magick/tool.rb', line 189

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



185
186
187
# File 'lib/mini_magick/tool.rb', line 185

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

Instance Method Details

#cli_optionsObject



249
250
251
252
253
254
255
256
257
# File 'lib/mini_magick/tool.rb', line 249

def cli_options
  tool = MiniMagick::Tool.new(@tool_name)
  tool << "-help"
  help_page = tool.call(false, stderr: false)

  cli_options = help_page.scan(/^\s+-[a-z\-]+/).map(&:strip)
  cli_options << "-gravity" if @tool_name == "mogrify" && MiniMagick.graphicsmagick?
  cli_options
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"


235
236
237
238
239
240
241
242
# File 'lib/mini_magick/tool.rb', line 235

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

#creation_operatorsObject



244
245
246
247
# File 'lib/mini_magick/tool.rb', line 244

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")
mogrify.command.join(" ")
#=> "mogrify -antialias -depth 8 -resize 500x500"


218
219
220
221
222
223
224
225
226
# File 'lib/mini_magick/tool.rb', line 218

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

#reload_methodsObject

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



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

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

#to_sObject



195
196
197
# File 'lib/mini_magick/tool.rb', line 195

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