2010-02-05 71 views
0

我試圖做出類似attr_reader的方法,但我似乎無法得到該方法被調用的類的實例。Ruby方法類似attr_reader

class Module 
    def modifiable_reader(*symbols) 
    # Right here is where it returns Klass instead of #<Klass:0x1df25e0 @readable="this"> 
    mod = self 

    variables = symbols.collect { |sym| ("@" << sym.to_s).to_sym } 
    attr_reader *symbols 

    (class << ModifyMethods; self; end).instance_eval do 
     define_method(*symbols) do 
     mod.instance_variable_get(*variables) 
     end 
    end 
    end 
end 

class Object 
    module ModifyMethods; end 
    def modify(&block) 
    ModifyMethods.instance_eval(&block) 
    end 
end 
class Klass 
    modifiable_reader :readable 

    def initialize 
    @readable = "this" 
    end 
end 

my_klass = Klass.new 
my_klass.modify do 
    puts "Readable: " << readable.to_s 
end 

回答

1

我不確定你想要做什麼。

如果有幫助,對attr_reader法術是這樣的:

#!/usr/bin/ruby1.8 

module Kernel 

    def my_attr_reader(symbol) 
    eval <<-EOS 
     def #{symbol} 
     @#{symbol} 
     end 
    EOS 
    end 

end 

class Foo 

    my_attr_reader :foo 

    def initialize 
    @foo = 'foo' 
    end 

end 

p Foo.new.foo  # => "foo" 
1

我可以從你的代碼明白的是,你想有modify塊到Klass實例方法作出迴應,這是就這麼簡單:

class Klass 
    attr_reader :modifiable 
    alias_method :modify, :instance_eval 

    def initialize(m) 
    @modifiable = m 
    end 

end 

Klass.new('john').modify do 
    puts 'Readable %s' % modifiable 
end 

關於本珍聞代碼:

def modifiable_reader(*symbols) 
    # Right here is where it returns Klass instead of #<Klass:0x1df25e0 @readable="this"> 
    mod = self 
    ... 

也許這能給你是怎麼回事的暗示:

Class.superclass # => Module 
Klass.instance_of?(Class) # => true 

Klass = Class.new do 
    def hello 
    'hello' 
    end 
end 
Klass.new.hello # => 'hello' 

當你添加方法的Module類,你也添加方法的Class類,它將一個實例方法添加到實例的Class(在這種情況下,您的類Klass),最後這意味着您正在您的Klass類添加類方法