class CapicuaGen::Generator

Clase generadora, nueclo de CapicuaGen, al que se le configuran todas las características y las llama segun corresponda para que generen la parte de código asociado a ellas

Attributes

argv_options[RW]
continue_on_failed[RW]
end_time[RW]
generation_attributes[RW]
local_templates[RW]
message_helper[RW]
retries[RW]
retry_failed[RW]
start_time[RW]

Public Class Methods

new(attributes= {}) { |self| ... } click to toggle source

Inicializo el objeto

# File lib/CapicuaGen/generator.rb, line 42
def initialize(attributes= {})
  initialize_properties(attributes, false)


  # Valores determinados
  @retry_failed          = true unless @retry_failed
  @retries               = 1 unless @retries
  @continue_on_failed    = true unless @continue_on_failed
  @local_templates       = 'Capicua' unless @local_templates

  # Colecciones de características que posee el generador
  @features              = []

  # Caraceristicas a ejecutar
  @targets               = []

  # Atributos generales de generación
  @generation_attributes = AttributeMixer.new

  # Configuro el gestor de mensajes
  @message_helper        = MessageHelper.new

  # Hora de comienzo y final
  @start_time            = Time.now
  @end_time              = Time.now

  # Opciones
  @argv_options          =OpenStruct.new

  # Aranco configuracion si es necesario
  yield self if block_given?
end

Public Instance Methods

add_feature(feature) click to toggle source

Agrega una característica en el generador

# File lib/CapicuaGen/generator.rb, line 90
def add_feature (feature)
  @features<<feature
end
add_feature_and_target(*features) click to toggle source

Agrega una característica y al mismo tiempo la convierte en objetivo

# File lib/CapicuaGen/generator.rb, line 131
def add_feature_and_target(*features)
  features.each do |feature|
    add_feature(feature)
    target= Target.new(:name => feature.name)
    add_target(target)
  end
end
add_target(target) click to toggle source

Agrega un objetivo

# File lib/CapicuaGen/generator.rb, line 120
def add_target(target)
  @targets<<target
end
clean(values ={}) click to toggle source

Genera todos las características

# File lib/CapicuaGen/generator.rb, line 260
def clean(values ={})
  @start_time = Time.now

  # Reviso argumentos
  if values[:arguments]
    arguments=Array(values[:arguments])
  else
    arguments=ARGV.clone
  end
  argv          =arguments
  @argv_options =parse_command_line(argv)

  return if @argv_options.exit

  @targets.each do |t|

    # configuro todas las asignaciones de generador

    feature          = get_feature_by_name(t.feature_name)
    feature.generator= self

  end

  # Clono los objetivos
  targets= [] + @targets
  retries= @retries + 1

  # Posibles reintentos
  retries.times do

    # Realizo las generaciones
    @targets.each do |t|

      next unless targets.include?(t)

      next unless t.enable_generation and t.enable

      feature= get_feature_by_name(t.feature_name)

      next if @argv_options.ignore_features.include? feature.name

      begin
        feature.clean
        targets.delete(t)
      rescue => e
        message_helper.puts_catched_error e
      end
    end

  end

  @end_time=Time.now

  puts
  message_helper.puts_end_generate(@start_time, @end_time)

end
features(values= {}) click to toggle source

Coleccion de características del generador

# File lib/CapicuaGen/generator.rb, line 76
def features(values= {})

  # Configuro los parametros por defecto
  enable_generation= nil
  enable           = true

  # Configuro los parametros
  enable_generation= values[:enable_generation] if values[:enable_generation]
  enable           = values[:enable_generation] if values[:enable_generation]

  return @features
end
generate(values={}) click to toggle source

Genera todos las características

# File lib/CapicuaGen/generator.rb, line 171
def generate(values={})

  no_arguments=values[:no_arguments]
  if values[:arguments]
    arguments=Array(values[:arguments])
  else
    arguments=ARGV.clone
  end

  start_time = Time.now

  # Reviso argumentos

  unless no_arguments
    argv          =arguments.clone
    @argv_options =parse_command_line(argv)

    return if @argv_options.exit

    if @argv_options.clean
      clean
    end

    if @argv_options.example
      generate_example
      return
    end

    generate_list if @argv_options.template_list

    generate_export_template @argv_options if @argv_options.template and not @argv_options.template_list

    return unless @argv_options.generate
  end

  @targets.each do |t|

    # configuro todas las asignaciones de generador

    feature          = get_feature_by_name(t.feature_name)
    feature.generator= self

  end

  # Clono los objetivos
  targets= [] + @targets
  retries= @retries + 1

  # Veo si debo hacer algo, si no muestro la ayuda
  if targets.blank?
    parse_command_line(["-h"])
    return
  end


  # Posibles reintentos
  retries.times do

    # Realizo las generaciones
    @targets.each do |t|

      next unless targets.include?(t)

      next unless t.enable_generation and t.enable

      feature= get_feature_by_name(t.feature_name)

      next if @argv_options and @argv_options.ignore_features and @argv_options.ignore_features.include? feature.name

      begin
        feature.generate
        targets.delete(t)
      rescue => e
        message_helper.puts_error_message "Error en característica '#{feature.name}' de tipo '#{feature.class}'"
        message_helper.puts_catched_error e
      end
    end

  end

  end_time=Time.now

  puts
  message_helper.puts_end_generate(start_time, end_time)

end
generate_example() click to toggle source
# File lib/CapicuaGen/generator.rb, line 319
def generate_example()

  arguments= ['generate']

  argv_options =parse_command_line(ARGV)


  generator_example = CapicuaGen::Generator.new do |g|

    # Creo las características necesarias
    feature_example = CapicuaGen::ExampleFeature.new(:name => 'feature_example')

    # Agrego las característica al generador
    g.add_feature_and_target feature_example

    # Configuro los atributos
    g.generation_attributes.add :out_dir => argv_options.out

  end


  arguments << "--force" if argv_options.force

  generator_example.generate :arguments => arguments

end
generate_export_template(options) click to toggle source
# File lib/CapicuaGen/generator.rb, line 365
def generate_export_template(options)
  templates=[]

  dir = File.join(File.dirname(__FILE__), '../../..')

  Dir["#{dir}/**/*"].select { |e| File.file? e and e=~/Template/ }.each do |template_file|


    feature_template=get_gem_type_feature(template_file)

    next unless feature_template

    next unless feature_template[:gem]=~ /#{options.template_gem}/
    next unless feature_template[:type]=~ /#{options.template_type}/
    next unless feature_template[:feature]=~ /#{options.template_feature}/


    out_file=File.join(options.template_out, feature_template[:gem], feature_template[:type], feature_template[:feature], File.basename(template_file))

    exists= File.exist?(out_file)

    if not exists or options.force

      # Creo el directorio
      FileUtils::mkdir_p File.dirname(out_file)
      FileUtils.cp template_file, out_file

      if exists
        message_helper.puts_copy_template(feature_template[:gem], feature_template[:type], feature_template[:feature], out_file, :override)
      else
        message_helper.puts_copy_template(feature_template[:gem], feature_template[:type], feature_template[:feature], out_file, :new)
      end

    else
      message_helper.puts_copy_template(feature_template[:gem], feature_template[:type], feature_template[:feature], out_file, :ignore)
    end


  end
end
generate_list() click to toggle source
# File lib/CapicuaGen/generator.rb, line 346
def generate_list
  templates=[]

  dir = File.join(File.dirname(__FILE__), '../../..')

  Dir["#{dir}/**/*"].select { |e| File.file? e and e=~/Template/ }.each do |f|

    feature_template=get_gem_type_feature(f)
    templates<<feature_template if feature_template

  end

  templates.uniq.each do |feature_template|
    message_helper.puts_list_template(feature_template[:gem], feature_template[:type], feature_template[:feature]) if feature_template
  end


end
get_feature_by_name(feature_name) click to toggle source

Obtiene la característica en base al nombre

# File lib/CapicuaGen/generator.rb, line 105
def get_feature_by_name(feature_name)
  return @features.detect { |f| f.name==feature_name }
end
get_feature_by_target_name() click to toggle source

Obtiene una característica, que a la vez es un objetivo, por su nombre

# File lib/CapicuaGen/generator.rb, line 141
def get_feature_by_target_name
  target @targets.detect { |f| f.name==feature_name }

  return unless target

  return get_feature_by_name(target.name)
end
get_features_by_type(feature_type) click to toggle source

Obtiene las caracteriscas de un tipo

# File lib/CapicuaGen/generator.rb, line 110
def get_features_by_type(feature_type)
  return @features.select { |f| f.type==type }
end
get_features_in_targets() click to toggle source

Obtiene una característica, que a la vez es un objetivo, por su tipo

# File lib/CapicuaGen/generator.rb, line 166
def get_features_in_targets
  return get_features_in_targets_by_type
end
get_features_in_targets_by_type(target_types= []) click to toggle source

Obtiene una característica, que a la vez es un objetivo, por su tipo

# File lib/CapicuaGen/generator.rb, line 150
def get_features_in_targets_by_type(target_types= [])
  features= []

  @targets.each do |t|
    feature= get_feature_by_name(t.feature_name)
    next unless feature
    next unless t.enable
    features<<feature if target_types.blank? or feature.is_any_type?(target_types)
  end

  return features

end
get_gem_type_feature(file) click to toggle source
# File lib/CapicuaGen/generator.rb, line 406
def get_gem_type_feature(file)
  if file=~/([^\/*]+)\/([^\/*?]+)\/([^\/*?]+)\/Template\//i
    return { :gem => $1, :type => $2, :feature => $3 }
  else
    return nil
  end
end
parse_command_line(args) click to toggle source

Parsea un linea de comamdos

# File lib/CapicuaGen/generator_command_line.rb, line 37
    def parse_command_line(args)

      options = OpenStruct.new

      options.ignore_features=[]

      opt_parser = OptionParser.new do |opts|
        opts.banner = "Uso: <Script generador> [comandos] [opciones]"

        opts.separator ""
        subtext = <<HELP
Comandos:
   generate          :     Genera las caracteriticas configuradas.
   clean             :     Limpia los archivos generados.
   cleanAndGenerate  :     Limpia los archivos generados y luego los vuelve a crear.
   example           :     Genera un ejemplo.
   template          :     Lista o permite reemplazar plantillas por defecto.


Ejecute '<generator.rb> COMMAND --help' para obtener más ayuda.
HELP
        opts.separator ""
        opts.separator subtext
        opts.separator ""

        # No argument, shows at tail.  This will print an options summary.
        # Try it and see!
        opts.on_tail("-h", "--help", "Muestra este mensaje.") do
          puts opts
          options.help=true
          options.exit=true
        end

        # Another typical switch to print the version.
        opts.on_tail("--version", "Muestra la versión.") do
          puts ::Version.join('.')
          options.version=true
          options.exit   =true
        end

      end

      subcommands = {

          'generate'         => OptionParser.new do |opts|

            opts.banner = "Uso: generate [options]"
            opts.separator ""

            # List of arguments.
            opts.on("--ignore featurename1, featurename2, featurename2", Array, "Lista de características que sera omitidas.") do |ignore_features|
              options.ignore_features = ignore_features
              options.ignore_features =[] unless options.ignore_features
            end

            opts.on("-f", "--force", "Fuerza que se sobreescriban las carateristicas generadas.") do
              options.force= true
            end

            opts.on_tail("-h", "--help", "Muestra este mensaje.") do
              puts opts
              options.help=true
              options.exit=true
            end
          end,


          'clean'            => OptionParser.new do |opts|

            opts.banner = "Uso: clean [options]"
            opts.separator ""

            # List of arguments.
            opts.on("--ignore featurename1, featurename2, featurename2", Array, "Lista de características que sera omitidas.") do |ignore_features|
              options.ignore_features = ignore_features
            end

            opts.on_tail("-h", "--help", "Muestra este mensaje.") do
              puts opts
              options.help=true
              options.exit=true
            end
          end,


          'cleanAndGenerate' => OptionParser.new do |opts|
            opts.banner = "Uso: example [options]"
            opts.separator ""
            opts.separator "Opciones:"
            opts.separator ""

            # List of arguments.
            opts.on("--ignore featurename1, featurename2, featurename2", Array, "Lista de características que sera omitidas.") do |ignore_features|
              options.ignore_features = ignore_features
            end

            opts.on("-f", "--force", "Fuerza que se sobreescriban las carateristicas generadas.") do
              options.force= true
            end

            opts.on_tail("-h", "--help", "Muestra este mensaje.") do
              puts opts
              options.help=true
              options.exit=true
            end

            opts.separator ""
          end,


          'example'          => OptionParser.new do |opts|
            opts.banner = "Uso: example [options]"
            opts.separator ""
            opts.separator "Opciones:"
            opts.separator ""

           
            opts.on("-o", "--out directorio", "Directorio de salida.") do |directorio|
              options.out = directorio
            end

            opts.on("-f", "--force", "Se sobreescribe el ejemplo.") do
              options.force= true
            end

            opts.on_tail("-h", "--help", "Muestra este mensaje.") do
              puts opts
              options.help=true
              options.exit=true
            end

            opts.separator ""
          end,


          'template'         => OptionParser.new do |opts|
            opts.banner = "Uso: template [options]"
            opts.separator ""
            opts.separator "Opciones:"
            opts.separator ""


            # List of arguments.
            opts.on("-l", "--list", "Lista los templates instalados.") do
              options.template_list = true
            end

            # Gema instalada
            opts.on("-g", "--gem gema", "Gema (instalada) a obtener.") do |template_gem|
              options.template_gem = template_gem
            end

            # Tipo de característica
            opts.on("-t", "--type tipo", "Tipos de carecteristica.") do |type|
              options.template_type = type
            end

            # Tipo de característica
            opts.on("-f", "--feature característica", "Carecteristica.") do |feature|
              options.template_feature = feature
            end

            # List of arguments.
            opts.on("-o", "--out directorio", "") do |directorio|
              options.template_out = directorio
            end

            opts.on_tail("-h", "--help", "Muestra este mensaje.") do
              puts opts
              options.help=true
              options.exit=true
            end

            opts.separator ""
          end
      }


      begin
        internal_args=args.clone
        opt_parser.order!(internal_args)
        command = internal_args.shift

        if command

          case command

            when 'generate'
              options.generate=true

            when 'clean'
              options.clean   =true
              options.generate=false

            when 'cleanAndGenerate'
              options.clean   =true
              options.generate=true

            when 'example'
              options.clean   =false
              options.generate=false
              options.example =true
              options.out     ='.'

            when 'template'
              options.clean        =false
              options.generate     =false
              options.template     =true
              options.template_out ='capicua'
          end

          subcommands[command].order! internal_args


        else
          options.generate=true
        end

      rescue => e
        $stderr.puts e
        puts
        puts opt_parser
        puts
        options.exit=true
      end


      return options
    end
remove_feature(feature) click to toggle source

Quita la característica

# File lib/CapicuaGen/generator.rb, line 95
def remove_feature (feature)
  @features.delete(feature)
end
remove_feature_by_name(feature_name) click to toggle source

Quita la caracterisitca en base al nombre

# File lib/CapicuaGen/generator.rb, line 100
def remove_feature_by_name(feature_name)
  @features.delete_if { |f| f.name==feature_name }
end
remove_target(target) click to toggle source

Elimina un objetivo

# File lib/CapicuaGen/generator.rb, line 125
def remove_target(target)
  @targets.delete(target)
end
targets() click to toggle source

Obtiene el nombre de todos los objetivos

# File lib/CapicuaGen/generator.rb, line 115
def targets
  return @targets
end