2014-03-27 41 views
0

我有以下代码:问题与创建DSL语法

module A 
    def self.included(base) 
    base.extend(ClassMethods) 
    end 
    def foo 
    a = bar 
    puts a 
    end 
    def bar(str="qwe") 
    str 
    end 

    module ClassMethods 
    end 
end 

class B 
    include A 
    def bar(str="rty") 
    str 
    end 
end 

B.new.foo #=> "rty" 

祝类B看起来像这样:

class B 
    include A 
    bar "rty" 
end 

B.new.foo #=> rty 

class B 
    include A 
    HelperOptions.bar "rty" # HelperOptions class should be in module A 
end 

B.new.foo #=> rty 

我试着用define_methodclass_evalinitialize。如何实现语法bar 'rty'HelperOptions.bar 'rty'以及模块A需要做什么?

回答

2

如果我得到你的问题正确,你要定义一个类的方法A.bar定义的实例方法B#bar返回它的参数,你可以做这样的:

module A 
    def self.included(base) 
    base.extend(ClassMethods) 
    end 
    def foo 
    puts bar 
    end 

    module ClassMethods 
    def bar(str) 
     define_method(:bar) { str } 
    end 
    end 
end 

class B 
    include A 
    bar 'rty' 
end 

B.new.bar 
# => "rty" 

B.new.foo 
# Output: rty 
+0

非常感谢,这是我的”寻找。 HelperOptions.bar的第二个变体呢?我如何为模块A中的类HelperOptions定义'bar'方法以使用语法类B;包括A; HelperOptions.bar'rty'; end –

+0

如果你想实现调用'HelperOptions.bar',你必须将'self'(即类'B')传递给'HelperOptions.bar'方法,这样你可以调用'B.send(:define_method,:酒吧)做...'。我不会推荐它。 – toro2k