使用Ruby模块进行默认设置

时间:2012-11-19 05:24:26

标签: ruby

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

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

这可能不是最好的方法,但这是我到目前为止所提出的。

这是一个为人们保留价值的模块Resume => 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 

然而,当我把它包含在一个类中它会抛出并且错误=&gt; 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类实例中输出include模块变量但是所有错误输出。

1 个答案:

答案 0 :(得分:0)

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