【问题标题】:Using a Ruby Module for Defaults使用 Ruby 模块进行默认设置
【发布时间】:2012-11-19 05:24:26
【问题描述】:

我想使用 Ruby 模块来存储一组配置默认值。

我在使用这些值时遇到了一些问题,希望有人能提供帮助。

这可能不是最好的方法,但这是我迄今为止想出的。

这是一个为个人简历保存价值的模块 => resume.rb

module Resume
  require 'ostruct'

  attr_reader :personal, :education

  @personal = OpenStruct.new

  @education = Array.new

  def self.included(base)
    set_personal
    set_education
  end

  def self.set_personal
    @personal.name          = "Joe Blogs"
    @personal.email_address = 'joe.blogs@gmail.com'
    @personal.phone_number  = '5555 55 55 555'
  end

  def self.set_education
    @education << %w{ School\ 1 Description\ 1 }
    @education << %w{ School\ 2 Description\ 2 }
  end
end

从 irb 可以正常工作:

% irb -I .
1.9.3-p194 :001 > require 'resume'
 => true 
1.9.3-p194 :002 > include Resume
 => Object 
1.9.3-p194 :003 > puts Resume.personal.name
Joe Blogs
 => nil 

但是,当我将它包含在一个类中时,它会抛出错误 => build.rb

require 'resume'

class Build
  include Resume

  def build
    puts Resume.personal.name
  end
end

来自 irb:

% irb -I .
1.9.3-p194 :001 > require 'build'
 => true 
1.9.3-p194 :002 > b = Build.new
 => #<Build:0x00000001d0ebb0> 
1.9.3-p194 :003 > b.build
NoMethodError: undefined method `personal' for Resume:Module
    from /home/oolyme/projects/lh_resume_builder_ruby/build.rb:7:in `build'
    from (irb):3
    from /home/oolyme/.rvm/rubies/ruby-1.9.3-p194/bin/irb:16:in `<main>'

我尝试了一些变体来输出 Build 类实例中的包含模块变量,但都出错了。

【问题讨论】:

    标签: ruby


    【解决方案1】:

    attr_accessor 创建了几个实例方法,这意味着它们将在Build 的实例上可用。但是您显然想要类实例方法。将模块的定义更改为:

    module Resume
      require 'ostruct'
    
      def self.personal
        @personal
      end
    
      def self.education
        @education
      end
    
      def self.included(base)
        @personal = OpenStruct.new
        @education = Array.new
    
        set_personal
        set_education
      end
    
      def self.set_personal
        @personal.name          = "Joe Blogs"
        @personal.email_address = 'joe.blogs@gmail.com'
        @personal.phone_number  = '5555 55 55 555'
      end
    
      def self.set_education
        @education << %w{ School\ 1 Description\ 1 }
        @education << %w{ School\ 2 Description\ 2 }
      end
    end
    

    它会起作用的

    b = Build.new
    b.build # >> Joe Blogs
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-20
      • 2011-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-11
      • 2016-08-11
      相关资源
      最近更新 更多