`
xu_wccq
  • 浏览: 133096 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

rails 细研base.rb(rails_generator)

阅读更多
lib/ruby/gems/1.8/gems/rails-1.2.3/lib/rails_generator/base.rb
require File.dirname(__FILE__) + '/options'
require File.dirname(__FILE__) + '/manifest'
require File.dirname(__FILE__) + '/spec'
require File.dirname(__FILE__) + '/generated_attribute'

module Rails
  # Rails::Generator is a code generation platform tailored for the Rails
  # web application framework.  Generators are easily invoked within Rails
  # applications to add and remove components such as models and controllers.
  # New generators are easy to create and may be distributed as RubyGems,
  # tarballs, or Rails plugins for inclusion system-wide, per-user, 
  # or per-application.
  #
  # For actual examples see the rails_generator/generators directory in the
  # Rails source (or the +railties+ directory if you have frozen the Rails
  # source in your application).
  #
  # Generators may subclass other generators to provide variations that
  # require little or no new logic but replace the template files.
  #
  # For a RubyGem, put your generator class and templates in the +lib+
  # directory. For a Rails plugin, make a +generators+ directory at the 
  # root of your plugin.
  #
  # The layout of generator files can be seen in the built-in 
  # +controller+ generator:
  #   
  #   generators/
  #     controller/
  #       controller_generator.rb
  #       templates/
  #         controller.rb
  #         functional_test.rb
  #         helper.rb
  #         view.rhtml
  #
  # The directory name (+controller+) matches the name of the generator file
  # (controller_generator.rb) and class (+ControllerGenerator+). The files
  # that will be copied or used as templates are stored in the +templates+
  # directory.
  #
  # The filenames of the templates don't matter, but choose something that
  # will be self-explatatory since you will be referencing these in the 
  # +manifest+ method inside your generator subclass.
  #
  # 
  module Generator
    class GeneratorError < StandardError; end
    class UsageError < GeneratorError; end


    # The base code generator is bare-bones.  It sets up the source and
    # destination paths and tells the logger whether to keep its trap shut.
    #
    # It's useful for copying files such as stylesheets, images, or 
    # javascripts.
    #
    # For more comprehensive template-based passive code generation with
    # arguments, you'll want Rails::Generator::NamedBase. 
    #
    # Generators create a manifest of the actions they perform then hand
    # the manifest to a command which replays the actions to do the heavy
    # lifting (such as checking for existing files or creating directories
    # if needed). Create, destroy, and list commands are included.  Since a
    # single manifest may be used by any command, creating new generators is
    # as simple as writing some code templates and declaring what you'd like
    # to do with them.
    #
    # The manifest method must be implemented by subclasses, returning a
    # Rails::Generator::Manifest.  The +record+ method is provided as a
    # convenience for manifest creation.  Example:
    #
    #   class StylesheetGenerator < Rails::Generator::Base
    #     def manifest
    #       record do |m|
    #         m.directory('public/stylesheets')
    #         m.file('application.css', 'public/stylesheets/application.css')
    #       end
    #     end
    #   end
    #
    # See Rails::Generator::Commands::Create for a list of methods available
    # to the manifest.
    class Base
      include Options

      # Declare default options for the generator.  These options
      # are inherited to subclasses.
      default_options :collision => :ask, :quiet => false

      # A logger instance available everywhere in the generator.
      cattr_accessor :logger

      # Every generator that is dynamically looked up is tagged with a
      # Spec describing where it was found.
      class_inheritable_accessor :spec

      attr_reader :source_root, :destination_root, :args

      def initialize(runtime_args, runtime_options = {})
        @args = runtime_args
        parse!(@args, runtime_options)

        # Derive source and destination paths.
        @source_root = options[:source] || File.join(spec.path, 'templates')
        if options[:destination]
          @destination_root = options[:destination]
        elsif defined? ::RAILS_ROOT
          @destination_root = ::RAILS_ROOT
        end

        # Silence the logger if requested.
        logger.quiet = options[:quiet]

        # Raise usage error if help is requested.
        usage if options[:help]
      end

      # Generators must provide a manifest.  Use the +record+ method to create
      # a new manifest and record your generator's actions.
      def manifest
        raise NotImplementedError, "No manifest for '#{spec.name}' generator."
      end

      # Return the full path from the source root for the given path.
      # Example for source_root = '/source':
      #   source_path('some/path.rb') == '/source/some/path.rb'
      #
      # The given path may include a colon ':' character to indicate that
      # the file belongs to another generator.  This notation allows any
      # generator to borrow files from another.  Example:
      #   source_path('model:fixture.yml') = '/model/source/path/fixture.yml'
      def source_path(relative_source)
        # Check whether we're referring to another generator's file.
        name, path = relative_source.split(':', 2)

        # If not, return the full path to our source file.
        if path.nil?
          File.join(source_root, name)

        # Otherwise, ask our referral for the file.
        else
          # FIXME: this is broken, though almost always true.  Others'
          # source_root are not necessarily the templates dir.
          File.join(self.class.lookup(name).path, 'templates', path)
        end
      end

      # Return the full path from the destination root for the given path.
      # Example for destination_root = '/dest':
      #   destination_path('some/path.rb') == '/dest/some/path.rb'
      def destination_path(relative_destination)
        File.join(destination_root, relative_destination)
      end

      protected
        # Convenience method for generator subclasses to record a manifest.
        def record
          Rails::Generator::Manifest.new(self) { |m| yield m }
        end

        # Override with your own usage banner.
        def banner
          "Usage: #{$0} #{spec.name} [options]"
        end

        # Read USAGE from file in generator base path.
        def usage_message
          File.read(File.join(spec.path, 'USAGE')) rescue ''
        end
    end


    # The base generator for named components: models, controllers, mailers,
    # etc.  The target name is taken as the first argument and inflected to
    # singular, plural, class, file, and table forms for your convenience.
    # The remaining arguments are aliased to +actions+ as an array for 
    # controller and mailer convenience.
    #
    # Several useful local variables and methods are populated in the 
    # +initialize+ method. See below for a list of Attributes and
    # External Aliases available to both the manifest and to all templates.    
    #
    # If no name is provided, the generator raises a usage error with content
    # optionally read from the USAGE file in the generator's base path.
    #
    # For example, the +controller+ generator takes the first argument as 
    # the name of the class and subsequent arguments as the names of
    # actions to be generated:
    #
    #   ./script/generate controller Article index new create
    #
    # See Rails::Generator::Base for a discussion of manifests, 
    # Rails::Generator::Commands::Create for methods available to the manifest,
    # and Rails::Generator for a general discussion of generators.
    class NamedBase < Base
      attr_reader   :name, :class_name, :singular_name, :plural_name, :table_name
      attr_reader   :class_path, :file_path, :class_nesting, :class_nesting_depth
      alias_method  :file_name,  :singular_name
      alias_method  :actions, :args

      def initialize(runtime_args, runtime_options = {})
        super

        # Name argument is required.
        usage if runtime_args.empty?

        @args = runtime_args.dup
        base_name = @args.shift
        assign_names!(base_name)
      end

      protected
        # Override with your own usage banner.
        def banner
          "Usage: #{$0} #{spec.name} #{spec.name.camelize}Name [options]"
        end
    
        def attributes
          @attributes ||= @args.collect do |attribute|
            Rails::Generator::GeneratedAttribute.new(*attribute.split(":"))
          end
        end


      private
        def assign_names!(name)
          @name = name
          base_name, @class_path, @file_path, @class_nesting, @class_nesting_depth = extract_modules(@name)
          @class_name_without_nesting, @singular_name, @plural_name = inflect_names(base_name)
          @table_name = ActiveRecord::Base.pluralize_table_names ? plural_name : singular_name
          if @class_nesting.empty?
            @class_name = @class_name_without_nesting
          else
            @table_name = @class_nesting.underscore << "_" << @table_name
            @class_name = "#{@class_nesting}::#{@class_name_without_nesting}"
          end
        end

        # Extract modules from filesystem-style or ruby-style path:
        #   good/fun/stuff
        #   Good::Fun::Stuff
        # produce the same results.
        def extract_modules(name)
          modules = name.include?('/') ? name.split('/') : name.split('::')
          name    = modules.pop
          path    = modules.map { |m| m.underscore }
          file_path = (path + [name.underscore]).join('/')
          nesting = modules.map { |m| m.camelize }.join('::')
          [name, path, file_path, nesting, modules.size]
        end

        def inflect_names(name)
          camel  = name.camelize
          under  = camel.underscore
          plural = under.pluralize
          [camel, under, plural]
        end
    end
  end
end

分享到:
评论

相关推荐

    Rails入门教程二(翻译)

    - `rails generate [generator] [args]`:用于生成代码模板,如模型、控制器等。 - `rails db:migrate`:执行数据库迁移,更新数据库结构。 #### 三、Rails教程示例:论坛程序开发 - **论坛程序设计**:本教程将...

    action_policy:RubyRails应用程序的授权框架

    行动方针 Ruby和Rails应用程序的授权框架。 可组合可扩展。... 这可以通过rails generate action_policy:install generator完成。 然后为资源编写策略。 例如: class PostPolicy &lt; ApplicationP

    service_it:[服务对象]简单的宝石,使您的控制器和模型苗条且易读

    └── name.rb 用法 class Foo &lt; ServiceIt :: Base def perform # put your logic here # you can use params that became variables end end 随时随地致电您的服务(控制器,模型,

    基于Retinex模型与多尺度融合的低光照图像增强算法及其应用

    内容概要:本文介绍了一种基于Retinex模型和多尺度融合的低光照图像增强算法。首先,通过对原图像进行光照图分解并利用Retinex模型进行估计,再经过伽马矫正获得亮度均衡的图像。接着,为补偿伽马矫正当中的过曝细节丢失,进行了锐化处理以提升图像细节。最后,在多尺度融合金字塔模型下,根据不同输入图像的权重进行融合,从而得到最终的增强图像。文中还详细介绍了五个非参考图像质量评价指标(BRISQUE,CEIQ,ENIQA,NIQE,PIQE),用以评估算法的效果。 适合人群:从事计算机视觉、图像处理领域的研究人员和技术人员。 使用场景及目标:适用于需要在低光照条件下获取高质量图像的各种应用场景,如安防监控、自动驾驶、医疗影像等领域。目的是提高图像的亮度、对比度和细节,确保后续图像处理任务的有效性和准确性。 其他说明:该算法不仅提高了低光照环境拍摄照片的质量,也为其他计算机视觉应用提供了更好的图像素材,具有重要的社会和经济价值。

    scratch少儿编程逻辑思维游戏源码-奔跑吧!忍者.zip

    scratch少儿编程逻辑思维游戏源码-奔跑吧!忍者.zip

    基于人工蜂群算法的智能路径规划系统:全局搜索、鲁棒性强、灵活多用的路径规划解决方案

    内容概要:本文详细介绍了基于人工蜂群算法的路径规划系统。该算法模拟蜜蜂觅食行为,通过多个个体的并行搜索,实现了全局搜索能力强、鲁棒性和适应性强、适用范围广、算法设计灵活以及具有分布式计算能力等特点。文中还提供了简化的代码片段,展示了如何实现地图创建、保存和起始地点更改等功能,进一步解释了算法的具体实现方法。 适合人群:对路径规划算法感兴趣的科研人员、工程师和技术爱好者。 使用场景及目标:适用于复杂环境下的单目标或多目标路径规划问题,旨在帮助研究人员和开发者更好地理解和应用人工蜂群算法,提升路径规划系统的性能和效率。 其他说明:该算法不仅在理论上具有较高的研究价值,还在实际应用中展现了广泛的潜力,特别是在智能交通、机器人导航等领域。

    基于鲸鱼算法优化LSSVM回归模型:提高预测准确率与全局优化能力

    内容概要:本文介绍了如何使用鲸鱼算法优化最小二乘支持向量机(LSSVM)的回归预测模型。通过模拟鲸鱼群体的行为,优化LSSVM中的惩罚参数和核惩罚参数,提高了预测的准确性和可靠性。鲸鱼算法具有广泛的适用性、强大的全局优化能力和高效的计算特点,使其成为解决各类回归预测问题的有效工具。文中还提供了具体的Python代码实现,展示了从基本LSSVM预测到参数优化的具体步骤,并通过实验数据验证了优化后的模型在训练时间和预测精度上的显著优势。 适合人群:对机器学习、优化算法感兴趣的开发者和技术研究人员,尤其是希望深入了解和支持向量机优化的人群。 使用场景及目标:适用于需要提高回归预测准确性的应用场景,如金融预测、气象预报等领域。目标是通过优化模型参数,获得更高的预测精度和更快的计算速度。 其他说明:鲸鱼算法不仅在理论上具有优越性,在实际应用中也能显著提升模型性能。建议根据具体的数据规模调整算法参数,以达到最佳效果。

    scratch少儿编程逻辑思维游戏源码-超级猫.zip

    scratch少儿编程逻辑思维游戏源码-超级猫.zip

    scratch少儿编程逻辑思维游戏源码-超级马里奥世界 多人游戏.zip

    scratch少儿编程逻辑思维游戏源码-超级马里奥世界 多人游戏.zip

    scratch少儿编程逻辑思维游戏源码-丛林探险跑酷.zip

    scratch少儿编程逻辑思维游戏源码-丛林探险跑酷.zip

    【java】智能自助式停车场管理系统后台web管理服务器javaweb项目.zip

    【java】智能自助式停车场管理系统后台web管理服务器javaweb项目

    二阶系统PID控制器设计与仿真的灵活性及性能优化研究

    内容概要:本文详细介绍了二阶系统的PID控制器设计与仿真方法,展示了如何通过MATLAB进行系统建模和控制器参数调整。首先构建了一个典型的二阶系统作为例子,通过设置不同的PID参数(比例P、积分I、微分D),演示了如何优化系统的阶跃响应特性。文中还讨论了不同参数对系统稳定性的影响,以及如何应对非线性环节带来的挑战。此外,作者强调了PID控制器参数调整的重要性,并提供了几种实用技巧,如使用MATLAB内置工具pidTuner进行参数整定,以及尝试更换不同的被控对象来测试控制器的适应性和鲁棒性。 适合人群:自动化工程专业学生、从事工业控制系统设计的技术人员、对PID控制感兴趣的科研工作者。 使用场景及目标:① 学习如何利用MATLAB搭建二阶系统并设计PID控制器;② 掌握PID参数调整的基本方法及其对系统性能的影响;③ 提升解决实际工业控制问题的能力,特别是在面对复杂动态环境时。 阅读建议:读者可以通过跟随文中的步骤,在自己的环境中重现实验结果,从而加深对PID控制理论的理解。同时,鼓励读者尝试修改系统参数或引入新的干扰因素,进一步探索PID控制器的应用边界。

    少儿编程scratch项目源代码文件案例素材-扫雷.zip

    少儿编程scratch项目源代码文件案例素材-扫雷.zip

    少儿编程scratch项目源代码文件案例素材-圣诞老人VS机器人.zip

    少儿编程scratch项目源代码文件案例素材-圣诞老人VS机器人.zip

    基于AT89C51单片机交通灯课程设计

    【基于AT89C51单片机的交通灯系统】是电子工程领域中的一个经典实践项目,尤其适合初学者进行单片机编程和硬件控制的学习。AT89C51是一款广泛应用的8位微处理器,由美国Atmel公司生产,具有4KB的可编程Flash存储器,可以执行各种控制任务,包括交通灯系统的控制。 交通灯控制系统是城市交通管理的重要组成部分,通过红绿黄三色灯的变化来指示行人和车辆何时通行。在本项目中,交通灯系统采用AT89C51单片机作为核心控制器,通过编程实现红绿黄灯的定时切换,确保交通流畅且安全。 DSN(Design Suite Notation)文件,如`C51交通灯.DSN`,通常是在电路设计软件,如Keil uVision或Proteus中创建的工程文件。这种文件包含了整个项目的配置信息,包括源代码、元器件库、仿真设置等,使得开发者可以在虚拟环境中对交通灯系统进行仿真测试。Proteus是一款强大的电子电路仿真软件,可以直观地模拟硬件电路的行为,无需物理硬件即可验证设计的正确性。 数码管(7段显示器)是显示倒计时的关键部件。在这个项目中,数码管用于显示每个灯组的剩余时间,增强用户交互体验,使驾驶员和行人能够清晰了解何时转换灯色。AT89C51通过串行或并行接口与数码管连接,并通过特定的驱动程序代码控制数码管的显示内容。 编程方面,AT89C51使用C51语言编写,这是一种为8051系列单片机定制的C语言变体。代码中包含的详细注释对于初学者理解程序逻辑至关重要,通过注释可以学习如何设置定时器、中断服务子程序以及I/O端口操作,这些都是单片机编程的基础知识。 交通灯的控制通常基于定时器中断,例如,可以设置一个定时器在特定周期后触发中断,然后在中断服务程序中改变灯的状态。此外,为了实现数码管显示,可能需要用到移位寄存器和译码器等外围设备,这些都需要在代码中进行编程控制。 这个项目涵

    基于MATLAB的改进带记忆模拟退火算法求解TSP问题(多普勒型降温曲线)

    内容概要:本文介绍了一种基于MATLAB的改进带记忆模拟退火算法用于求解旅行商问题(TSP)。该算法引入了多普勒型降温曲线和记忆功能,使得算法在前期进行全局搜索而在后期进行精细调整。文中详细展示了算法的核心代码片段,如多普勒型降温曲线的实现和记忆功能的具体实现方式。此外,作者提供了对多个经典数据集(如att48、中国31/64/144城市数据)的测试结果,证明了该算法的有效性和优越性。同时,还给出了自定义数据集的测试方法和路径可视化的代码。 适合人群:对优化算法感兴趣的研究人员和技术爱好者,尤其是那些希望深入了解模拟退火算法及其应用的人群。 使用场景及目标:适用于需要解决复杂组合优化问题的场景,特别是涉及路径规划、物流配送等领域。目标是提供一种高效、稳定的解决方案,帮助用户快速获得高质量的解。 其他说明:本文不仅提供了完整的代码实现,还包括详细的解释和测试实例,便于读者理解和实践。对于想要进一步探索或修改算法的人来说,这是一个很好的起点。

    MMC-HVDC电能质量调节系统及其背靠背模块化多电平换流器在电网与粒子加速器中的应用

    内容概要:本文详细介绍了MMC-HVDC电能质量调节系统及其背靠背模块化多电平换流器(MMC)的工作原理和技术优势。MMC-HVDC系统主要用于保护敏感电网免受瞬态电压骤降的影响,通过内部能量存储和整流器控制线路电流,确保电网的稳定性。此外,该系统还具备无功功率补偿、低谐波失真和高冗余性的特点。文中特别提到MMC-HVDC在粒子加速器领域的应用和发展前景,强调了其在复杂环境中的适应性和可靠性。 适合人群:从事电力系统工程、电能质量管理、粒子加速器设计的研究人员和技术人员。 使用场景及目标:适用于需要解决瞬态电压骤降问题的电力系统,特别是在粒子加速器等对电能质量有较高要求的场合。目标是提高电网的稳定性和效率,减少设备损坏和系统不稳定性。 其他说明:文章还讨论了MMC-HVDC的设计和开发过程,包括模块化结构设计、能量存储优化和控制算法改进等方面的内容。

    少儿编程scratch项目源代码文件案例素材-侵略者.zip

    少儿编程scratch项目源代码文件案例素材-侵略者.zip

    scratch少儿编程逻辑思维游戏源码-暴徒危机.zip

    scratch少儿编程逻辑思维游戏源码-暴徒危机.zip

    少儿编程scratch项目源代码文件案例素材-收缩剑.zip

    少儿编程scratch项目源代码文件案例素材-收缩剑.zip

Global site tag (gtag.js) - Google Analytics